php - Replace characters in a PHP string skipping specific domain extensions
问题描述
I have a long string and would like to replace every dot "." with a question mark, however my string includes domain extensions such as .com which I would like to skip when replacing.
Is there any way I can provide an array such as (".com", ".net", ".org") of phrases to skip when replacing using str_replace() or a similar function?
Input sentence:
$string = "An example of a website would be google.com or similar. However this is not what we are looking for";
The following:
str_replace(".", "?", $string);
Produces:
An example of a website would be google?com or similar? However this is not what we are looking for
Desired output:
An example of a website would be google.com or similar? However this is not what we are looking for
I would like to provide an array of domain extensions to skip, when replacing. Such as:
$skip = array(".com",".net",".org");
and wherever those appear, don't substitute the dot with a question mark.
EDIT: Looks like I need to use a negative lookahead with preg_replace. However not sure how to put it all together: "look for a full stop that is NOT followed by COM or NET or ORG.
解决方案
You need
$result = preg_replace('~\.(?!(?:com|org|net)\b)~', '?', $string);
See the regex demo. Details
\.
- a dot(?!
- not followed with(?:com|org|net)
-com
,org
,net
substrings...\b
- as whole words (it is a word boundary)
)
- end of the negative lookahead.
NOTE: to make the TLDs match in a case insensitive way, add i
after the trailing regex delimiter, here, ~i
.
See a 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
推荐阅读
- python - 如何在python中使用numpy来做流向栅格单元
- javafx - 当以编程方式更改 ComboBox 值属性时,如何防止触发 ActionEvent?
- apache-flink - 使用 FsStateBackend 在 Kubernetes 中进行 Flink 检查点失败
- node.js - 如何为桌面、Web 和移动应用程序(Electron.JS、Angular、NativeScript)创建可共享库
- tomcat - 如何在 Windows Server 2016 中使用 tomcat 配置 Stackify 前缀?
- python - Pygame矩形都聚在一起
- blazor - 在 Blazor 中显示可重用的 VueJS 图表组件
- python - 在散景图中选择和更新熊猫数据框列
- spring - ::TIMESTAMP::DATE 在 Java/Spring 中工作吗?
- python - 错误框中的混淆矩阵值