简体   繁体   English

正则表达式将从内容中找到字符串并替换为HTML标记

[英]Regex which will find string from content and replace with HTML tag

I have a content like this. 我有这样的内容。

"Test with the dummy content. Another dummy content."

I want regex where If I pass specific string and specific html tag then It will replace string with tag. 我想要正则表达式,如果我传递特定的字符串和特定的html标签,那么它将用标签替换字符串。 For ex. 对于前者

function strReplace($content, $string, $tag)
{
    // $output = regex function ...

}

If I call method like strReplace($content, 'dummy', 'b'); 如果我调用类似strReplace的方法($ content,'dummy','b');

Output should be: 输出应该是:

"Test with the <b>dummy</b> content. Another <b>dummy</b> content."

Thanks in advance 提前致谢

You're searching for preg_split : http://php.net/manual/en/function.preg-split.php 您正在搜索preg_splithttp//php.net/manual/en/function.preg-split.php

You can split on the regex, receive the fragment and then insert after the first and before the last element your tags. 您可以在正则表达式上拆分,接收片段,然后在第一个元素和标记的最后一个元素之后插入。 This is probably (depending on your context) even so possible with just str_split . 这可能(取决于您的上下文)甚至可能只用str_split

Find solution. 找到解决方案

Tried something and it works. 尝试了一些事情并且有效。 Using regex like 使用正则表达式

// $tag = '<b>'; or $tag = 'b';
$tag = str_replace('<', '', str_replace('>', '', $tag));

$output = preg_replace(array('/'.$string.'/'), array('<'.$tag.'>'.$string.'</'.$tag.'>'), $content);

Thanks for help still suggestions are always welcome. 感谢您的帮助,我们随时欢迎您的建议。

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

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