在我的一个 PHP 网站上,我使用 this regular expression自动从字符串中删除电话号码:
$text = preg_replace('/\+?[0-9][0-9()-\s+]{4,20}[0-9]/', '[删除]', $text);
但是,当用户发布包含多个数字的长 URL 作为其文本的一部分时,该 URL 也会受到 preg_replace
的影响,这会破坏该 URL。
如何确保上述 preg_replace
不会改变 $text
中包含的 URL?
编辑:
根据要求,这是一个 URL 被上面的 preg_replace
破坏的例子:
$text = 'Please help me with my question here: https://stackoverflow.com/questions/20589314/ Thanks!';
$text = preg_replace('/\+?[0-9][0-9()-\s+]{4,20}[0-9]/', '[removed]', $text);
echo $text;
//echoes: Please help me with my question here: https://stackoverflow.com/questions/[removed]/ Thanks!
最佳答案
我认为你必须解析 url 和电话号码,比如 /(?: url\K | phone number)/
- sln
@sln:我该怎么做?如果有帮助,这里有一个 URL 正则表达式:stackoverflow.com/a/8234912/869849
– ProgrammerGirl
这是一个使用提供的正则表达式作为 url 和电话号码的示例:
PHP测试用例
$text = 'Please help me with my +44-83848-1234 question here: http://stackoverflow.com/+44-83848-1234questions/20589314/ phone #:+44-83848-1234-Thanks!';
$str = preg_replace_callback('~((?:(?:[a-zA-Z]{3,9}:(?://)?)(?:[;:&=+$,\w-]+@)?[a-zA-Z0-9.-]+|(?:www\.|[;:&=+$,\w-]+@)[a-zA-Z0-9.-]+)(?:(?:/[+\~%/.\w-]*)?\??[+=&;%@.\w-]*\#?\w*)?)|(\+?[0-9][0-9()\s+-]{4,20}[0-9])~',
function( $matches ){
if ( $matches[1] != "" ) {
return $matches[1];
}
return '[removed]';
},
$text);
print $str;
输出>>
Please help me with my [removed] question here: http://stackoverflow.com/+44-83848-1234questions/20589314/ phone #:[removed]-Thanks!
正则表达式,用RegexFormat
处理
# '~((?:(?:[a-zA-Z]{3,9}:(?://)?)(?:[;:&=+$,\w-]+@)?[a-zA-Z0-9.-]+|(?:www\.|[;:&=+$,\w-]+@)[a-zA-Z0-9.-]+)(?:(?:/[+\~%/.\w-]*)?\??[+=&;%@.\w-]*\#?\w*)?)|(\+?[0-9][0-9()\s+-]{4,20}[0-9])~'
( # (1 start), URL
(?:
(?:
[a-zA-Z]{3,9} :
(?: // )?
)
(?: [;:&=+$,\w-]+ @ )?
[a-zA-Z0-9.-]+
|
(?: www \. | [;:&=+$,\w-]+ @ )
[a-zA-Z0-9.-]+
)
(?:
(?: / [+~%/.\w-]* )?
\??
[+=&;%@.\w-]*
\#?
\w*
)?
) # (1 end)
|
( # (2 start), Phone Num
\+?
[0-9]
[0-9()\s+-]{4,20}
[0-9]
) # (2 end)
关于php - 如果是 URL 的一部分,如何忽略正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20589314/