需要正则表达式在长单词中添加空格但忽略html标签和属性

pag*_*gex 4 php regex split

我需要在用户提供的位置(例如我们会说25)中在产品描述中的单词中添加空格以允许正确的包装.我知道可以使用css技巧,但这不是我喜欢的东西.

到目前为止,我可以使用这种语法来做到这一点,但我遇到的问题是它的分裂内容不应该像html标记属性中的URL一样分裂.

    $string = 'longwordlongwordlongword <a href="http://www.somelongdomainname.com/and-a-long-sub-directoty_name" class="some_long_class_name_here">someanchortext and title here</a>';

    $spacer = 20;

    $newtext = preg_replace('/([^\s]{' . $spacer . '})(?=[^\s])/m', '$1 ', $newtext);
Run Code Online (Sandbox Code Playgroud)

结果是......

    longwordlongwordlong word <a href="http://www.som elongdomainname.com/ and-a-long-sub-direc toty_name" class="some_long_cla ss_name_here">somean chortext and title here</a>
Run Code Online (Sandbox Code Playgroud)

所以基本上我需要以某种方式告诉正则表达式除了html标签和属性之外的一切.

任何帮助都是极好的.谢谢.

Tim*_*ker 6

如果你确定<>你的HTML文件的属性值或注释中永远不会有尖括号(),那么你可以试试这个:

$result = preg_replace(
    '/(        # Match and capture...
     [^\s<>]   # anything except whitespace and angle brackets
     {20}      # 20 times.
    )          # End of capturing group.
    (?!        # Assert that it\'s impossible to match the following:
     [^<>]*    # any number of characters except angle brackets
     >         # followed by a closing bracket.
    )          # End of lookahead assertion.
    /x', 
    '\1 ', $subject);
Run Code Online (Sandbox Code Playgroud)

这里的想法是仅当文本中的下一个尖括号不是右括号时才匹配20个字符的非空格字符串(这意味着该字符串在标记内).如果在其他地方可能出现尖括号,显然这会中断.

您可能还想使用\w而不是[^\s<>],因此您实际上只匹配字母数字字符串(如果这是您想要的).