繁体   English   中英

如何用链接替换子字符串?

[英]How can I replace a substring with a link?

我在第6到第11位的文本中有一个字符串,我想用HTML链接替换它

我该怎么做?

$text = 'hello world this is my question , plz help';
$position_from = 15;
$position_to = 20;
$link = 'http://google.com';

我需要一个函数给我这个:

$text = 'hello <a href="http://google.com">world</a> this is my question , plz help';

要使用相同子字符串的修改版本替换子字符串,首先通过从结束位置减去起始位置来计算要替换的子字符串的长度。

$len = $to - $from;

然后你可以使用substrsubstr_replace进行替换:

$link = '<a href="http://google.com">' . substr($text, $from, $len) . '</a>';
$text = substr_replace($text, $link, $from, $len);

或使用带有preg_replace的正则表达式替换。

$pattern = "/(?<=^.{{$from}})(.{{$len}})/";
$text = preg_replace($pattern, '<a href="http://www.google.com">$1</a>', $text);

对于多字节安全操作,由于没有mb_substr_replace ,您可以重复使用mb_substr

$text = mb_substr($text, 0, $from)
        . "<a href='$url'>" . mb_substr($text, $from, $len) . '</a>'
        . mb_substr($text, $to);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM