Php 在给定字符串上设置特定单词样式的函数?
如何从给定字符串中设置特定单词的样式Php 在给定字符串上设置特定单词样式的函数?,php,Php,如何从给定字符串中设置特定单词的样式 $myString = "foo bar"; 如何使一个函数在字符串中找到一个给定单词时加粗,然后再次返回该字符串 $formattedString = Bold('foo',$myString); echo $formattedString ; 预期结果:foo bar 我该怎么做?我需要根据键入的用户查询在搜索结果中加粗一些关键字/短语 任何帮助都将不胜感激最简单的方法是使用str_replace(“foo”、“foo”和$string) 也可以使用
$myString = "foo bar";
如何使一个函数在字符串中找到一个给定单词时加粗,然后再次返回该字符串
$formattedString = Bold('foo',$myString);
echo $formattedString ;
预期结果:foo bar 我该怎么做?我需要根据键入的用户查询在搜索结果中加粗一些关键字/短语
任何帮助都将不胜感激最简单的方法是使用
str_replace(“foo”、“foo”和$string)
也可以使用RegExp
执行相同的操作
更新:要获得更高级的样式设置功能,您可以使用RegExp
下一步:
function bold($text, array $words) {
return preg_replace('/\b('.implode('|', $words).')\b/i', '<b>$1</b>', $text);
}
通过这种方式,您可以通过向$tag
参数发送标记名(b
用于
例如)来删除您的文本,甚至为任何一组单词加下划线。您的意思是:
function Bold($text, $str) {
return str_replace($text, "<strong>".$text."</strong>", $str);
}
echo Bold("test", "this is a test");
函数粗体($text,$str){
返回str_replace($text,“”。$text.”,$str);
}
echo Bold(“测试”,“这是测试”);
使用发布的str_replace解决方案,当您的单词作为另一个单词的一部分被发现时,您将遇到问题。例如,在Sudhir的示例中,如果$str是“这是一个使用Testostron的测试”(抱歉,缺少更好的示例),那么输出将是
这是一个测试与测试的测试
要解决此问题,可以使用正则表达式,因为您有单词边界表达式:
function bold($string, $word)
{
return preg_replace('/\b'.$word.'\b/', '<strong>'.$word.'</strong>', $string);
}
echo bold('this is a test with testosteron', 'test');
函数粗体($string,$word)
{
返回preg_replace('/\b'.$word'.\b/',''.$word'.',$string);
}
echo bold(“这是一个使用Testostron的测试”,“测试”);
当单词被不能被视为单词一部分的元素包围时,该规则将匹配您的单词我认为这对字符串“this is a test”或“this is atest”没有帮助,因为它只搜索“test”而不是它的标记。我认为这对字符串“this is a test with testosteron”或“这是一个测试,带有测试osteron”,因为它只搜索“测试”,而不是tags@ShikataGaNai,看看我的解决方案。它应该是您想要的(它与单词一起工作,而不是像str\u replace()
does这样的字符集)。我们在项目中使用类似的方法。
function bold($string, $word)
{
return preg_replace('/\b'.$word.'\b/', '<strong>'.$word.'</strong>', $string);
}
echo bold('this is a test with testosteron', 'test');