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

后端 未结 5 411
小鲜肉
小鲜肉 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: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.

提交回复
热议问题