【问题标题】:How can I replace a substring with a link?如何用链接替换子字符串?
【发布时间】:2016-12-04 10:47:06
【问题描述】:

我有一个从位置 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';

【问题讨论】:

  • 您想用链接替换word?或&lt;link&gt;word&lt;/link&gt;

标签: php string replace substring


【解决方案1】:

要用相同子字符串的修改版本替换子字符串,首先计算要替换的子字符串的长度,方法是从结束位置减去开始位置。

$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);

【讨论】:

  • 好电话。我不认为 original 单词应该 dynamically 坚持到新字符串。
  • 谢谢!我认为这让这个问题变得更有趣了。
  • 谢谢!并且我使用 mb_substr 而不是 substr 因为波斯语......但是没有 mb_substr_replace ! utf8 怎么做?
  • @MiLaDTNT 我编辑了答案以显示仅使用 mb_substr 的一种方法。
猜你喜欢
  • 2015-09-10
  • 1970-01-01
  • 2016-09-29
  • 2015-11-13
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多