簡體   English   中英

使用正則表達式包裝句子中的單詞

[英]Wrapping words in a sentence using 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標簽內,並用&nbsp;替換單詞的字符。 並保留特殊字符。,:; !!?¿¡和空格。

使用正則表達式可以解決嗎? 實際上,我通過使用非非常有效的循環來解決此問題,該循環掃描字符串的每個字符,但是我必須在每頁掃描許多句子。

使用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) ))
$yourphrase = preg_replace('/([^\W]+)/si', '<span>$1</span>', $yourphrase);

這將用跨號包裹所有“ _ ”-詞...

恕我直言,您需要在此執行兩步操作,首先,必須將字母轉換為下划線(這顯然已經奏效了嗎?),其次,您必須將“ _ ”-單詞包裹在一個跨距中(使用我的正則表達式)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM