Page 1 of 1

problem with preg_replace

Posted: Sat Oct 28, 2006 8:10 pm
by winsonlee
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Somehow after running the code my output turn out to be 

"hello how are you mr James" and not
"hello how are you there good morning mr James"

what regular expression should i be using to code in such that it replace words that is within the two script to an empty space and not replacing words that is within the first script and the last script ?

Code: Select all

$str = 'hello how are you <script> xxxxx </script> there good morning<script> zzzzz </script> mr James ';
convert_html($str);

function convert_html($text) {
       $temp = $text;
       $html_code[0] = '/(<script>)(.*)(<\/script>)/';       
       $html_replace[0] = '';

       $temp2 = preg_replace($html_code, $html_replace, $temp);
			 return $temp2;
   }

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Sat Oct 28, 2006 8:13 pm
by volka
pcre by default is greedy, i.e. each quantifier matches as much characters as it can. Therefore
<script> xxxxx </script> there good morning<script> zzzzz </script>
is a single match where the (.*) covers the green substring.


see http://de2.php.net/manual/en/reference. ... ifiers.php , U (PCRE_UNGREEDY)

Posted: Sat Oct 28, 2006 8:55 pm
by winsonlee
Thanks. I manage to solve the problem.