php - 需要正则表达式在长词中添加空格但忽略 HTML 标记和属性

标签 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);

结果是这样的....

    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>

我需要以某种方式告诉正则表达式拆分除 HTML 标记和属性之外的所有内容。

最佳答案

如果您确定永远不会在 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);

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

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

关于php - 需要正则表达式在长词中添加空格但忽略 HTML 标记和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641058/

相关文章:

javascript - 使用正则表达式替换 innerHTML 文本时的性能问题

python - 基于 Pandas 中竖线分隔的列创建多个新行

mysql - 如何计算逗号分隔列中的出现次数?

php - 检查帐户是否存在

php - 如何在飞行PHP框架上使用mysqli

php - 如何使用 ajax-json 和 php-postgresql 避免编码问题

php - MySQL查询行为怪异

c# - .NET 正则表达式 - 较短的匹配

java - 正则表达式,只需要用逗号分隔

vba - 列表框下标超出范围excel vba