我有一个从位置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;
然后您可以使用substr
和substr_replace
:进行更换
$link = '<a href="http://google.com">' . substr($text, $from, $len) . '</a>';
$text = substr_replace($text, $link, $from, $len);
或者用CCD_ 3代替使用正则表达式。
$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);