我需要在产品描述中用户提供的位置(例如 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/