I am using preg_match()
to extract pieces of text from a variable, and let's say the variable looks like this:
[htmlcode]This is supposed to be displayed[/htmlcode]
middle text
[htmlcode]This is also supposed to be displayed[/htmlcode]
i want to extract the contents of the [htmlcode]
's and input them into an array. i am doing this by using preg_match()
.
preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}
The above code outputs
[htmlcode]This is supposed to be displayed[/htmlcode]middle text[htmlcode]This is also supposed to be displayed[/htmlcode]
instead of
and if have offically run out of ideas
As explained already; the *
pattern is greedy. Another thing is to use preg_match_all()
function. It'll return you a multi-dimension array of matched content.
preg_match_all('#\[htmlcode\]([^\"]*?)\[/htmlcode\]#ms', $text, $matches);
foreach( $matches[1] as $value ) {
And you'll get this: http://codepad.viper-7.com/z2GuSd
A *
grouper is greedy, i.e. it will eat everything until last [/htmlcode]
. Try replacing *
with non-greedy *?
.
*
is by default greedy, ([^\"]*?)
(notice the added ?
) should make it lazy.
Look at this piece of code:
preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}
Now, if your pattern works fine and all is ok, you should know:
return
statement will break all loops and will exit the function.$text
So, what you did is returned the first big string and exited the function.
I suggest you can check for desired results:
$matches[1]
and $matches[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With