Jump to content

[SOLVED] Further problems with preg_match..


Adam

Recommended Posts

Continuing my last topic which I frst thought was solved (http://www.phpfreaks.com/forums/index.php/topic,231586.0.html) .. I have a new problem, with the expression:

 

\[pre\].+?\[\/pre\]

 

With preg_replace it replaces all occurences of the matched string, but preg_match only seems to match the first?

 

$str = '[tag]This should be replaced with ::tag:: and added to $matches[/tag] .. [tag]So should this![/tag] But this shouldn\'t!';

preg_match('#\[tag\].+?\[\/tag\]#', $str, $matches);
$str = preg_replace('#\[tag\].+?\[\/tag\]#', '::tag::', $str);

print 'After preg_replace: ' . $str . '<br />Matches from preg_match:<pre>';
print_r($matches);
print '</pre><br /><br />';

 

That will return something like:

 

After preg_replace: ::tag:: .. ::tag:: But this shouldn't!

Matches from preg_match:

 

Array

(

    [0] => [tag]This should be replaced with ::tag:: and added to $matches[/tag]

)

 

I'm stuck ??? Anyone?

 

Cheers!

 

A

Link to comment
Share on other sites

Hah of course, I even knew that function existed just never thought about it. Though reading the PHP manual, it doesn't make it particularly clear that it only returns the first result. Ah well, sorted now thanks a lot!

 

A

Link to comment
Share on other sites

From the manual:

 

 

Return Values

 

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject . preg_match() returns FALSE if an error occurred.

 

Dunno how much clearer you expect them to be....

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.