php - 使以 * 开头的单词加粗

标签 php string

字符串中所有以*开头的单词都应该是粗体。 这是我到目前为止所尝试过的:

$string = "This is *a string to *check *bold";
echo preg_replace('/*(\w+)/', '<b>\1</b>', $string);

这给了我错误:

This is *a string to *check *bold Warning: preg_replace(): Compilation failed: nothing to repeat at offset 0 in...

最佳答案

你有错误的preg_replace()正则表达式

* 是正则表达式中的特殊字符,应该转义。我使用 # 作为分隔符以获得更好的可见性。

检查下面的代码:

$string = "This is *a string to *check *bold";
echo preg_replace('#\*(\w+)#', '<b>$1</b>', $string);

关于php - 使以 * 开头的单词加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31317889/

相关文章:

php - PHP公告: Undefined index: in a line

php - 在 PHP 5.3.8 和 NOT xampp 中找不到规范器

php - 在将数据库值传递给 View 之前修改数据库值

C++ boost 正则表达式 : How to find all possible string constants from C/C++ code?

javascript - 如何在反引号中创建反引号?

检查元音的 JavaScript 函数

Javascript 时间与 PHP 时间,不一样

javascript - AJAX仅发送一次post请求

javascript - 在 JavaScript 中拆分字符串并检测换行符

java - 递归查找句子中最长的单词