这是一个基本的preg_replace,可以检测电话号码(和长号码)。我的问题是,我希望避免检测双""、单''和正斜杠//之间的数字
$text = preg_replace("/(\+?[\d-\(\)\s]{8,25}[0-9]?\d)/", "<strong>$1</strong>", $text);
我到处找了找,但什么都不管用。您的帮助我们将不胜感激。
发布于 2019-09-15 06:54:59
看起来您并没有验证,那么您可能会尝试编写一些边界较少的表达式,例如:
^\+?[0-9()\s-]{8,25}[0-9]$如果您希望简化/修改/探索该表达式,可以在regex101.com的右上角面板中对其进行解释。如果您愿意,您还可以在this link中观看它如何与一些样本输入进行匹配。
发布于 2019-09-15 15:27:50
我预测你的模式会让你失望,而不是让你满意(或者你对项目范围内的“过度匹配”非常满意)。
虽然我的建议确实超出了模式长度,但(*SKIP)(*FAIL)技术通过使用和丢弃需要取消限定的子字符串,将为您提供足够好的服务。也许有一种方法可以用lookaround来指示模式逻辑,但由于初始模式中有如此多的潜在漏洞,并且没有样本数据,因此有太多的变量无法做出自信的建议。
代码:(Demo)
$text = <<<TEXT
A number 555555555 then some more text and a quoted number "(123)4567890" and
then 1 2 3 4 6 (54) 3 -2 and forward slashed /+--------0/ versus
+--------0 then something more realistic '234 588 9191' no more text.
This is not closed by the same character on both
ends: "+012345678901/ which of course is a _necessary_ check?
TEXT;
echo preg_replace(
'~([\'"/])\+?[\d()\s-]{8,25}\d{1,2}\1(*SKIP)(*FAIL)|((?!\s)\+?[\d()\s-]{8,25}\d{1,2})~',
"<strong>$2</strong>",
$text);输出:
A number <strong>555555555</strong> then some more text and a quoted number "(123)4567890" and
then <strong>1 2 3 4 6 (54) 3 -2</strong> and forward slashed /+--------0/ versus
<strong>+--------0</strong> then something more realistic '234 588 9191' no more text.
This is not closed by the same character on both
ends: "<strong>+012345678901</strong>/ which of course is a _necessary_ check?有关技术细目,请参阅Regex101链接。
否则,这将有效地检查“电话号码”(根据您的初始模式),如果它们被'、"或/包装,那么匹配将被忽略,正则表达式引擎将继续在该子字符串之后查找匹配。我在第二次使用您的电话模式时添加了(?!\s),以便替换时省略前导空格。
https://stackoverflow.com/questions/57366380
复制相似问题