Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 positive integer inside of parentheses, I'd like to replace that with simply the integer itself.

The code I'm using now is:

$result = preg_replace("((d+))", "$0", $string);

But I keep getting a

Delimiter must not be alphanumeric or backslash.

Warning

Any thoughts? I know there are other questions on here that sort of answer the question, but my knowledge of regex is not enough to switch it over to this example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...