Search code examples
phppreg-replacestrip

How to strip out extra asterisks in a string using preg_replace()


I know how to strip out extra spaces, dashes, and periods using preg_replace(), but I need to know what format below is correct for stripping out extra asterisks in a string.

These lines of code work for stripping out extra spaces, dashes, and periods:

// Strips out extra spaces
   $string = preg_replace('/\s\s+/', ' ',$string);
// Strips out extra dashes
   $string = preg_replace('/-+/', '-', $string);
// Strips out extra periods
   $string = preg_replace('/\.+/', '.', $string);

Which of the following is correct for stripping out extra asterisks?

// Version 1: Strips out extra asterisks
   $string = preg_replace('/\*+/', '*', $string);

// Version 2: Strips out extra asterisks
   $string = preg_replace('/*+/', '*', $string);

Thank you in advance.

By the way, is there a list somewhere that shows all the characters that need to be escaped with a forward slash when using PHP?


Solution

  • Try this:

    $string = preg_replace('/\*{2,}/', '*', $string);
    

    This will replace any instances of multiple asterisks next to one another with one asterisk.

    Or, if you wanted to just get rid of all asterisks:

    $string = preg_replace('/[\*]+/', '', $string);
    

    It's worth noting that * is a special character in regular expressions; so, you must escape it with a backslash.

    Also, here's a good regex reference: http://www.regular-expressions.info/reference.html

    Here's how you could combine multiple character replacements into one regex:

    $string = preg_replace('/(\*|\.){2,}/', '$1', $string);
    

    This will replace asterisks as well as periods.