Sunday 15 July 2012

regex - php preg_replace replace each occurrence when a multiple match -


I have a string that contains multiple * to represent the show rating I like people other than ratings * To represent the thing, one person can use, if two or more are (for example, **), then I would assume that they only represent the rating.

I want to change every event * when it is in the rating to improve the presentation (& amp; # 9733;)

I am currently using preg_replace , As are the matches found for two or more frequencies

  $ blurb = preg_replace ("/ [\ *] {2,} /", "& # 9733; ", $ S ['long description']);   

This, however, just puts it in one place ★ No matter how many incidents how can I modify it to change every event?

For example, ** becomes ★★, *** becomes ★★★ etc.

You can use a custom callback for this and:

 < Code> $ blurb = preg_replace_callback ("/ ([\ *] {2,} /", function ($ match) {return str_repet ("& amp; # 9733;", strollen ($ match [1]); }, $ S ['long description']); With an input string of   

***** , this output will be:

  & amp; # 9733; & Amp; # 9733; & Amp; # 9733; & Amp; # 9733; & Amp; # 9733;   

For PHP & lt; 5.3, you will not be able to use an anonymous function, so you have to declare the above callback as a standalone function. However, if you want to be super-ultra-cool, you can modify your regex to use the claim, and you can get all the stars that come before or after an asterisk, such as: / P>

  $ s ['long description'] = 'replace these ***** not * and *** it ** ****'; $ Blurb = preg_replace ("/ (?: (? & Lt; = \ *) | (? = \ * \ *) * *", "& # 9733;", $ s ['long description']);   

regex ensures that from the present state, we either saw just one star, or see two asterisks in front of us, if any of those claims is true, Attempt to capture.

This:

  In & amp; # 9733; & Amp; # 9733; Replace & # 9733; & Amp; # 9733; & Amp; # 9733; Not this * and & amp; # 9733; & Amp; # 9733; & Amp; # 9733; This & amp; # 9733; & Amp; # 9733; & Amp; # 9733; & Amp; # 9733; & Amp; # 9733; & Amp; # 9733;    

No comments:

Post a Comment