TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Why does this preg_match fail? (http://www.talkphp.com/general/5179-why-does-preg_match-fail.html)

benton 12-21-2009 02:08 PM

Why does this preg_match fail?
 
Can someone plase explain why this statement fails?
PHP Code:

preg_match('/<h1>(*)<\/h1>/i'$line$matches); 

The failure results in the warning
Quote:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 5
If I enter this line instead (just to test the code), it works.
PHP Code:

preg_match('/<b class="main">(.*)<\/b>/i'$line$matches); 


girvine 12-21-2009 05:37 PM

Looks like your missing a dot.

In the first statement,
(*)
should be,
(.*)

benton 12-21-2009 07:08 PM

Thanks. Unfortunately, that was just a typo made while editing the post. The original code already had it in there. I did find that using quotes instead of apostrophes made a difference though. So this now works:
PHP Code:

preg_match("/<td align=\"right\" valign=\"top\"><h1>(.*)<\/h1><\/td>/i"$line$matches); 

I had to add more code in the check to get it to work.

So the next step is to read that in from the database so it works without manual edits. This is what I am trying to do (the top line is simulating what would be read from the database):
PHP Code:

$search_str '<td align="right" valign="top"><h1>(.*)</h1></td>';
$search_str str_replace("/""\\/"$search_str);
$search_str str_replace('"''\\"'$search_str);
$condition '"/'.$search_str '/i"';

preg_match($condition$line$matches); 

That doesn't create any erros and when I look at the source, the $condition appears exactly as when I type it in directly but the match isn't found. Does anyone have any suggestions on what might make this fail?

girvine 12-21-2009 08:16 PM

If I take out the quotes around the condition and don't escape the quotes inside the condition,

PHP Code:

$search_str '<td align="right" valign="top"><h1>(.*)</h1></td>'
$search_str str_replace("/""\\/"$search_str); 
$condition '/'.$search_str '/i'

preg_match($condition$line$matches); 

it seems to work.

benton 12-22-2009 12:57 AM

That did it. Thanks for taking the time to help. It is much appreciated. :)


All times are GMT. The time now is 10:05 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0