过滤字符串中以“?”开头的单词,并将它们放在 <span> - PHP 中


Filter a string for words that starts with a "?" and put them in a <span> - PHP

我想做的是过滤一个像这样的字符串:

"?group This is a title"

然后输出如下内容:

<span class="group">group</span> This is a title

我的问题是:PHP可以做到这一点吗?我怎么能做这样的事情?

试试这个

$text = preg_replace('/'?('w+)/', '<span class="$1">$1</span>', $text);

这是你需要的:

$string = "wordt bla shit happends and this wil be ?fat and ?this";
$array = array();
// Wanna search on other characters change the second ? and not the first. The first ? is part of the syntax.
preg_match_all('/(?<!'w)'?'w+/', $string, $array);
$result = $array[0];
foreach($result as $value){
    $word = ltrim($value,'?');
    // in your case change the html to whatever you want
    $string = str_replace($value,"<b>$word</b>",$string);
}
echo $string;

结果将是:

wordt bla shit happends and this wil be <b>fat</b> and <b>this</b>
$text = preg_replace('/'?('w+)/', '<span class="$1">$1</span>', $text);