RegEx包装范围标记

时间:2017-08-08 15:13:57

标签: php html

正如标题所示,我试图将每个单词包装在<span>标签服务器端。但我错过了正确的RegEx。

我当前的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>标签包装每个单词。

1 个答案:

答案 0 :(得分:0)

使用此代码:

试试这个正则表达式:

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

示例:

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