当重复的子字符串时如何正确替换字符串?

问题描述 投票:0回答:2

我想将超链接添加到文本中的url,但是问题是我可以使用不同的格式,并且url可能具有在其他字符串中重复的某些子字符串。让我用一个例子更好地解释它:

Here I have one insidelinkhttp://google.com But I can have more formats like the followings: https://google.com google.com

现在,我从上面的示例中提取了以下链接:["http://google.com", "https://google.com", "google.com"],我想用以下数组替换那些匹配项:['<a href="http://google.com">http://google.com</a>', '<a href="https://google.com">https://google.com</a>', '<a href="google.com">google.com</a>']

如果我迭代替换每个元素的数组,将出现错误,如上例所示,一旦我为"http://google.com"正确添加了超链接,每个子字符串将被"google.com"中的另一个超链接替换

任何人都知道如何解决该问题?

感谢

php replace repeat str-replace regexp-replace
2个回答
0
投票

您可以进行搜索并将其替换为模板字符串。例如:STRINGA,STRINGB,STRINGC

然后遍历数组,其中项目0替换了STRINGA。只需确保模板名称没有重叠的名称,例如STRING1和STRING10


0
投票

根据您的示例字符串,我定义了3种不同的URL匹配模式,并根据您的要求将其替换,您可以在“ $ regEX”变量中定义更多模式。

// string
$str = "Here I have one insidelinkhttp://google.com But I can have more formats like the followings: https://google.com google.com";

/**
 * Replace with the match pattern
 */
function urls_matches($url1)
{
  if (isset($url1[0])) {
    return '<a href="' . $url1[0] . '">' . $url1[0] . '</a>';
  }
}

// regular expression for multiple patterns
$regEX = "/(http:\/\/[a-zA-Z0-9]+\.+[A-Za-z]{2,6}+)|(https:\/\/[a-zA-Z0-9]+\.+[A-Za-z]{2,6}+)|([a-zA-Z0-9]+\.+[A-Za-z]{2,6}+)/";

// replacing string based on defined patterns
$replacedString = preg_replace_callback(
  $regEX,
  "urls_matches",
  $str
);

// print the replaced string
echo $replacedString;
© www.soinside.com 2019 - 2024. All rights reserved.