"word1 word-6ren">
gpt4 book ai didi

php - 替换尚未替换的字符串

转载 作者:搜寻专家 更新时间:2023-10-31 21:19:26 24 4
gpt4 key购买 nike

所以我有这样的文字:

"word1 word2 word3 etc"

我有一个数组,其中包含一组替换项,我必须像这样携带:

[    
"word1 word2" => "<a href="someurl">word1 word2</a>",
"word2" => "<a href="someurl">word2</a>",
"word3" => "<a href="someurl">word3</a>"
]

基本上我必须为某些单词(或它们的组合)添加一些标签。

我需要避免这种情况,因为“word1 word2”已经被这样替换了:

<a href="someurl">word1 word2</a> word3 etc

我需要避免它变成这样:

"<a href="someurl">word1 <a href="someurl">word2</a></a> word3 etc"
^^^ another replacement inside "word1 word2"

如何避免替换已在其他替换中找到的较小字符串?

使用 str_replace 的实时代码不工作:

$array = [    
"word1 word2" => "<a href='someurl'>word1 word2</a>",
"word2" => "<a href='someurl'>word2</a>",
"word3" => "<a href='someurl'>word3</a>"
];

$txt = "word1 word2 word3 etc";

echo str_replace(array_keys($array),array_values($array),$txt);

http://sandbox.onlinephpfunctions.com/code/85fd62e88cd0131125ca7809976694ee4c975b6b

正确输出:

<a href="someurl">word1 word2</a> <a href="someurl">word3</a> etc

最佳答案

试试这个:

$array = [    
"word1 word2" => "<a href='someurl'>word1 word2</a>",
"word2" => "<a href='someurl'>word2</a>",
"word3" => "<a href='someurl'>word3</a>"
];

$txt = "word1 word2 word3 etc";

foreach ($array as $word => $replacement) {
if (!stripos($txt, ">$word<") && !stripos($txt, ">$word") && !stripos($txt, "$word<") ){
$txt = str_replace($word, $replacement, $txt);
}
}
echo $txt;

// output: <a href='someurl'>word1 word2</a> <a href='someurl'>word3</a> etc

基本上,在替换单词之前,检查它是否已经包含在标签中

关于php - 替换尚未替换的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com