2

How do you change this to a preg_replace() equivalent (without using a loop)?

Note: $text is utf-8.

  do $text = str_replace("* *", "*", $text, $totRepla); while ($totRepla);
2
  • Please provide a text example. Commented Apr 27, 2011 at 18:55
  • thaks to the one that change the subject. I was afraid about an horible google indexing top rank on a tribial and poorly formulated question Commented Apr 27, 2011 at 19:19

4 Answers 4

2

I believe the regexp pattern to match an arbitrary long * * * * * * is

/(\* )*\*/

Please add the rest of the code yourself, I don't have PHP handy right now to provide a full code snippet.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks i will use: /(* )+*/ all other exposed solutions, do not reduce multiple ocurences to just one.
Would you try to benchmark your initial solution against regex one? It's interesting which runs faster :D
I'm sure it depends on how match consecutive asterisks do the $text have. I bet regex is more eficient (cos compilated) with more than 10 on the input string. If you write the code I run it on my server also.
1

Actually, String functions are much more efficient then regex, I see no reason using regex if you have a working solution using str_replace.

http://php.net/manual/en/function.str-replace.php

see documentation:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().

1 Comment

str_replace() isn't necessarily more efficient if it's used in a do ... while loop.
0
preg_replace('/\* \*/', '*', $totRepla);

1 Comment

That will still require the while loop.
0

The PCRE equivalent of that is:

$text = preg_replace('~(?:[*] )+[*]~', '*', $text);

Your code suggests that you have no interest in knowing how many replacements occurred, so you don't need the $totRepla variable. However, if I am wrong, this is the way to get that count:

$text = preg_replace('~(?:[*] )+[*]~', '*', $text, -1, $totRepla);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.