【问题标题】:Replace characters in a PHP string skipping specific domain extensions替换跳过特定域扩展的 PHP 字符串中的字符
【发布时间】:2021-07-04 08:55:54
【问题描述】:

我有一个长字符串,想替换每个点“。”带有问号,但是我的字符串包含域扩展名,例如 .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 的句号。

【问题讨论】:

  • 你已经用 regex 和 preg replace 标记了这个。您是否尝试过使用正则表达式?我在你的问题中没有看到。
  • 我不确定要使用什么正则表达式,也找不到任何东西。
  • 你有没有对正则表达式做过任何真正的研究,它是如何工作的并尝试过什么? regex101.com 是一个非常好的测试(和学习)正则表达式的网站。
  • @WiktorStribiżew 是的,我已经看到了那个链接,但是我不确定如何将它应用到我的需要中。看起来我需要使用负前瞻,例如 (?!.*bar) 但不确定如何将其与:查找句号 > 后面没有 COM、ORG 或 NET。有人可以帮忙吗?

标签: php regex replace preg-replace str-replace


【解决方案1】:

你需要

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多