使用preg_replace的PHP:“分隔符不得为字母数字或反斜杠";错误 [英] PHP using preg_replace : "Delimiter must not be alphanumeric or backslash" error
本文介绍了使用preg_replace的PHP:“分隔符不得为字母数字或反斜杠";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试像这样输入一串文字:
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.
我现在使用的代码是:
$result = preg_replace("\((\d+)\)", "$0", $string);
但是我不断得到一个
分隔符不能为字母数字或反斜杠.
Delimiter must not be alphanumeric or backslash.
警告
有什么想法吗?我知道这里还有其他问题可以回答该问题,但是我对正则表达式的了解不足以将其切换到本示例.
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.
推荐答案
您快到了.您正在使用:
You are almost there. You are using:
$result = preg_replace("((\d+))", "$0", $string);
- 您指定为第一个的正则表达式
preg_*
函数族的参数 应该成对分隔 定界符.由于您没有使用 任何定界符,您都会收到该错误. -
(
和)
是正则表达式中的元字符, 表示它们具有特殊的含义. 由于您要匹配文字打开 圆括号和近圆括号, 您需要使用\
对其进行转义.\
之后的所有内容都将被处理 从字面上看. - 您可以捕获整数
正确使用
\d+
.但是被俘 整数将在$1
中而不是$0
中.$0
将拥有整个比赛,即 括号内的整数. - 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);
这篇关于使用preg_replace的PHP:“分隔符不得为字母数字或反斜杠";错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文