PHP using preg_replace : “Delimiter must not be alphanumeric or backslash” error

后端 未结 5 395
小鲜肉
小鲜肉 2020-11-29 08:08

I am trying to take a string of text like so:

$string = \"This (1) is (2) my (3) example (4) text\";

In every instance where there is a pos

相关标签:
5条回答
  • 2020-11-29 08:23

    You are almost there. You are using:

    $result = preg_replace("((\d+))", "$0", $string);
    
    • The regex you specify as the 1st argument to preg_* family of function should be delimited in pair of delimiters. Since you are not using any delimiters you get that error.
    • ( and ) are meta char in a regex, meaning they have special meaning. Since you want to match literal open parenthesis and close parenthesis, you need to escape them using a \. Anything following \ is treated literally.
    • You can capturing the integer correctly using \d+. But the captured integer will be in $1 and not $0. $0 will have the entire match, that is integer within parenthesis.

    If you do all the above changes you'll get:

    $result = preg_replace("#\((\d+)\)#", "$1", $string);
    
    0 讨论(0)
  • 2020-11-29 08:24

    Try:

    <?php
    $string = "This (1) is (2) my (3) example (4) text";
    $output = preg_replace('/\((\d)\)/i', '$1', $string);
    echo $output;
    ?>
    

    The parenthesis chars are special chars in a regular expression. You need to escape them to use them.

    0 讨论(0)
  • 2020-11-29 08:37

    Check the docs - you need to use a delimiter before and after your pattern: "/\((\d+)\)/"

    You'll also want to escape the outer parentheses above as they are literals, not a nested matching group.

    See: preg_replace manual page

    0 讨论(0)
  • 2020-11-29 08:40

    1) You need to have a delimiter, the / works fine.

    2) You have to escape the ( and ) characters so it doesn't think it's another grouping.

    3) Also, the replace variables here start at 1, not 0 (0 contains the FULL text match, which would include the parentheses).

    $result = preg_replace("/\((\d+)\)/", "\\1", $string);
    

    Something like this should work. Any further questions, go to PHP's preg_replace() documentation - it really is good.

    0 讨论(0)
  • 2020-11-29 08:49

    Delimiter must not be alphanumeric or backslash.,

    try typing your parameters inside "/ .... /" as shown bellow. Else the code will output >>> Delimiter must not be alphanumeric or backslash.

    $yourString='hi there, good friend';
    $dividorString='there';
    $someSstring=preg_replace("/$dividorString/",'', $yourString);
    
    echo($someSstring);
    
    // hi, good friend
    

    . . worked for me.

    0 讨论(0)
提交回复
热议问题