使用正则表达式在句子中包装单词

时间:2012-08-28 02:06:27

标签: php regex

我正在转换句子:

Phasellus turpis, elit. Tempor et lobortis? Venenatis: sed enim!

为:

_________ ______, ____. ______ __ ________? _________: ___ ____!

使用:

utf8_encode(preg_replace("/[^.,:;!?¿¡ ]/", "_", utf8_decode($ss->phrase) ))

但是我遇到了一个问题:Google正在将所有这些空单词编入索引作为关键字。我想将原始字符串转换为Google不可见的内容,例如:

<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span> <span>&nbsp;&nbsp;&nbsp;&nbsp</span>, ....   

使用:

.parent span { text-decoration:underline; }

也就是说,在span标签内包装单词,用&amp; nbsp;替换单词'并且保留了特殊字符。:;!?¿¡和空间。

使用正则表达式可以解决这个问题吗?我实际上通过使用一个非常有效的循环来扫描字符串的每个字符来解决这个问题,但我必须每页扫描很多句子。

2 个答案:

答案 0 :(得分:1)

使用preg_replace_callback并让回调创建相应的替换。 (未经测试的)

的东西
function replacer($match) {
    return "<span>".str_repeat("&nbsp;",strlen($match[1]))."</span>";
}

// Note the addition of the () and the + near the end of the regex
utf8_encode(preg_replace_callback("/([^.,:;!?¿¡ ]+)/", "replacer", utf8_decode($ss->phrase) ))

答案 1 :(得分:0)

$yourphrase = preg_replace('/([^\W]+)/si', '<span>$1</span>', $yourphrase);

这将包装所有“ _ ” - 带有跨度的单词......

你需要一个两步的程序,首先你必须把字母转换为下划线(这显然已经有了吗?), 第二,你必须包装“ _ ” - 跨度中的单词(使用我的正则表达式)。

相关问题