2017-08-08 143 views
0

正如標題所示,我試圖將每個單詞都包含在<span>標記服務器端。但我錯過了正確的RegEx。正則表達式包裹span標記中的每個單詞

我目前的PHP代碼如下所示。

function exampleFunction($text) 
{ 

    $re1 = '/(<.*>)(.*)(<\/.*>)/'; 
    $str = $text; 
    preg_match_all($re1, $str, $matches, PREG_SET_ORDER, 0); 

    $result = NULL; 
    foreach($matches as $key => $value) { 
    $words = $value[2]; 
    $start_tag = $value[1]; 
    $end_tag = $value[3]; 

    $re2 = '/(\w+|.)/'; 
    preg_match_all($re2, $words, $word_matches, PREG_SET_ORDER, 0); 

    $paragraph = $start_tag; 

    foreach($word_matches as $key => $value) { 
     if($value[0] != " ") { 
     $paragraph .= '<span>'.$value[0].'</span>'; 
     } else { 
     $paragraph .= $value[0]; 
     } 
    } 
    $paragraph .= $end_tag; 
    $result .= $paragraph; 
    } 
    return $result; 

} 

替換的不是唯一的問題..

當我把像

<h1>Hello, dudes</h1> 
<p>This stackoverflow test text. Using all special chars like üöä and some 
spicy ß or ? and !. What do u think about some() or % worth about 5000$ or 
€? Iam not sure, but that should be enough. And a link to <a href="google.com">google</a> would be awesome. Whats about further text? Thats buggy, 
isnt it? üöä ?ßß</p> 

我得到

<h1><span>Hello</span><span>,</span> <span>dudes</span></h1><p>This 
stackoverflow test text. Using all special chars like üöä and some spicy ß 
or ? and !. What do u think about some() or % worth about 5000$ or €? Iam 
not sure, but that should be enough. And a link to <a 
href="http://google.com">google</a> <span>would</span> <span>be</span> 
<span>awesome</span><span>.</span> <span>Whats</span> <span>about</span> 
<span>further</span> <span>text</span><span>?</span> <span>Thats</span> 
<span>buggy</span><span>,</span> <span>isnt</span> <span>it</span><span>? 
</span> <span>�</span><span>�</span><span>�</span><span>�</span> 
<span>�</span><span>�</span> <span>?</span><span>ßß</span></p> 

後, <a>這就是我需要的,除了奇怪的特殊字符。有人可以幫我解決嗎?我沒有明白這一點。老實說,我認爲我只需要正確的正則表達式來包裝每個字<span>標籤。

回答

0

使用此代碼:

試試這個正則表達式:

var str = "This string... it's, an. example! <em>string</em>?!"; 
str.replace(/([A-z0-9'<>/]+)/g, '<span>$1</span>'); 

例子:

var str = "This string... it's, an. example! <em>string</em>?!"; 
 
str = str.replace(/([A-z0-9'<>/]+)/g, '<span>$1</span>'); 
 
console.log(str);

相關問題