【问题标题】:Need regex to add spaces in long words but ignore HTML tags and attributes需要正则表达式在长词中添加空格但忽略 HTML 标记和属性
【发布时间】:2011-07-10 12:20:34
【问题描述】:

我需要在用户提供的位置(例如我们会说 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 标记和属性之外的所有内容。

【问题讨论】:

  • 只需要替换第一个&lt;a&gt;吗?字符串中是否只有一个标签,即&lt;a&gt;
  • 不要使用正则表达式:stackoverflow.com/questions/1732348/…
  • 您应该以编程方式执行此操作。 Regex 无法做到这一点。

标签: php regex split


【解决方案1】:

如果您确定在 HTML 文件的属性值或 cmets 中永远不会有尖括号 (&lt;&gt;),那么您可以试试这个:

$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&lt;&gt;],因此您实际上只匹配字母数字字符串(如果这是您想要的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 2020-08-06
    • 2011-08-12
    • 1970-01-01
    • 2013-06-16
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多