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

Php 当有重复的子字符串时,如何正确地替换字符串?,php,replace,repeat,str-replace,regexp-replace,Php,Replace,Repeat,Str Replace,Regexp Replace,我想在文本中添加指向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

我想在文本中添加指向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“]
我想用以下数组替换这些匹配项:
[“”,,“”]

如果我在数组上迭代替换每个元素,那么一旦我正确地添加了
的超链接,就会出现上述示例中的错误。”http://google.com“
每个子字符串都将替换为
“google.com”

有人知道如何解决这个问题吗


谢谢

您可以进行搜索并将其替换为TemplateString。 e、 g.:STRINGA、STRINGB、STRINGC

然后在项目0替换STRINGA的数组上循环。
只需确保模板名称没有重叠的名称,如STRING1和STRING10

根据您的示例字符串,我定义了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;
//字符串
$str=“我这里有一个内部文件elinkhttp://google.com 但我可以有更多的格式,如以下:https://google.com 谷歌网站”;
/**
*替换为匹配模式
*/
函数URL\u匹配($url1)
{
如果(isset($url1[0])){
返回“”;
}
}
//多模式正则表达式
$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}/”;
//根据定义的模式替换字符串
$replacedString=preg_replace_回调(
$regEX,
“URL\u匹配”,
$str
);
//打印替换的字符串
echo$replacedString;

您试过了吗?非常感谢!它工作得很好,我真的很感谢你的帮助:)