【问题标题】:Filter a string for words that starts with a "?" and put them in a <span> - PHP过滤以“?”开头的单词的字符串并将它们放在 <span> - PHP
【发布时间】:2013-10-07 05:42:00
【问题描述】:

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

"?group This is a title"

然后输出如下内容:

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

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

【问题讨论】:

标签: php string


【解决方案1】:

试试这个

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

【讨论】:

  • 啊,你的更短了!!
【解决方案2】:

这是你需要的:

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

【讨论】:

    【解决方案3】:
    $text = preg_replace('/\?(\w+)/', '<span class="$1">$1</span>', $text);
    

    【讨论】:

    • 感谢您的回答 :) 但这还不完全正确。现在我得到这个输出: group This is a title
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    相关资源
    最近更新 更多