problem with preg_replace

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
winsonlee
Forum Commoner
Posts: 76
Joined: Thu Dec 11, 2003 8:49 pm

problem with preg_replace

Post 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]
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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)
winsonlee
Forum Commoner
Posts: 76
Joined: Thu Dec 11, 2003 8:49 pm

Post by winsonlee »

Thanks. I manage to solve the problem.
Post Reply