Jump to content


[PHP] preg_replace


3 replies to this topic

#1 Ryzie

    Young Padawan

  • Members
  • Pip
  • 11 posts

Posted 07 November 2007 - 06:09 AM

Any ideas why this doesn't work?
It's meant to make everything inside the [lol] tags uppercase

<?php
$html_body = "[lol]lkol test ijoisahd[/lol]";
echo preg_replace("/\[lol\](.*?)\[\/lol\]/is",
			 '<pre class="lol">'.strtoupper($1).'</pre>',
			 $html_body);
?>


#2 Mr. Matt

    Moderator

  • P2L Staff
  • PipPipPipPip
  • 1,945 posts
  • Gender:Not Telling

Posted 07 November 2007 - 10:33 AM

This is how I would do it:

$html_body = 'This is my block of HTML text. [lol]This is wrapped[/lol] and [lol]this is wrapped[/lol].';

if( preg_match_all( '¬\[lol\](.*?)\[\/lol\]¬', $html_body, $matches ) ) {
	
	for( $i = 0; $i <= count( $matches[1] ); $i++ ) {
	
		$html_body = str_replace( $matches[0][$i], '<pre class="lol">' . strtoupper( $matches[1][$i] ) . '</pre>', $html_body );

	}

}

echo $html_body;

First of all I would do a preg_match_all as preg_match will just find one occurance of it, whilst preg_match_all will find all occurances. Then whilst looping through them I would use the str_replace as generally it is quicker to do that then a preg_replace.

Hope that helps

Matt

#3 rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 07 November 2007 - 06:51 PM

Good solution, but the question was "why" doesn't it work...

preg_replace_callback()
Pattern Modifiers (specifically 'e')

I can't give you a short explaination, just understand that what you were expecting to happen is not implied by the language. What you're trying is similar to that of BBcode ['code'] tags... do a forum search on it, i believe there is an explaination amongst one of the posts here about it.

#4 Ryzie

    Young Padawan

  • Members
  • Pip
  • 11 posts

Posted 08 November 2007 - 03:35 AM

Thankyou very much Mr.Matt.
That is exactly what I was looking for.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users