替换 PHP 字符串中的字符,跳过特定的域扩展
Replace characters in a PHP string skipping specific domain extensions
我有一个长字符串,想替换每个点“.”带有问号,但是我的字符串包含域扩展名,例如 .com,我想在替换时跳过它。
在使用 str_replace() 或类似函数进行替换时,有什么方法可以提供一个数组,例如 (".com", ".net", ".org") 要跳过的短语?
输入句子:
$string = "An example of a website would be google.com or similar. However this is not what we are looking for";
以下:
str_replace(".", "?", $string);
产生:
An example of a website would be google?com or similar? However this is not what we are looking for
期望的输出:
An example of a website would be google.com or similar? However this is not what we are looking for
我想提供一组域扩展名,以便在替换时跳过。如:
$skip = array(".com",".net",".org");
无论出现在哪里,都不要用问号代替点。
编辑:看来我需要对 preg_replace 使用否定前瞻。但是不确定如何将它们放在一起:“寻找 COM、NET 或 ORG 后面没有的句号。
你需要
$result = preg_replace('~\.(?!(?:com|org|net)\b)~', '?', $string);
见regex demo。
详情
\.
- 一个点
(?!
- 后面没有
(?:com|org|net)
- com
、org
、net
子字符串...
\b
- 作为整个单词(它是一个单词边界)
)
- 负前瞻结束。
注意:要使 TLD 以不区分大小写的方式匹配,请在结尾的正则表达式定界符后添加 i
,此处为 ~i
.
看到一个PHP demo:
$string = "An example of a website would be google.com or similar. However this is not what we are looking for";
$tlds = ['com', 'org', 'net'];
echo preg_replace('~\.(?!(?:' . implode('|', $tlds) . ')\b)~i', '?', $string);
// => An example of a website would be google.com or similar? However this is not what we are looking for
我有一个长字符串,想替换每个点“.”带有问号,但是我的字符串包含域扩展名,例如 .com,我想在替换时跳过它。
在使用 str_replace() 或类似函数进行替换时,有什么方法可以提供一个数组,例如 (".com", ".net", ".org") 要跳过的短语?
输入句子:
$string = "An example of a website would be google.com or similar. However this is not what we are looking for";
以下:
str_replace(".", "?", $string);
产生:
An example of a website would be google?com or similar? However this is not what we are looking for
期望的输出:
An example of a website would be google.com or similar? However this is not what we are looking for
我想提供一组域扩展名,以便在替换时跳过。如:
$skip = array(".com",".net",".org");
无论出现在哪里,都不要用问号代替点。
编辑:看来我需要对 preg_replace 使用否定前瞻。但是不确定如何将它们放在一起:“寻找 COM、NET 或 ORG 后面没有的句号。
你需要
$result = preg_replace('~\.(?!(?:com|org|net)\b)~', '?', $string);
见regex demo。 详情
\.
- 一个点(?!
- 后面没有(?:com|org|net)
-com
、org
、net
子字符串...\b
- 作为整个单词(它是一个单词边界)
)
- 负前瞻结束。
注意:要使 TLD 以不区分大小写的方式匹配,请在结尾的正则表达式定界符后添加 i
,此处为 ~i
.
看到一个PHP demo:
$string = "An example of a website would be google.com or similar. However this is not what we are looking for";
$tlds = ['com', 'org', 'net'];
echo preg_replace('~\.(?!(?:' . implode('|', $tlds) . ')\b)~i', '?', $string);
// => An example of a website would be google.com or similar? However this is not what we are looking for