我有一些 html 段落,我想用 .我现在有

$paragraph = "This is a paragraph.";
$contents = explode(' ', $paragraph);
$i = 0;
$span_content = '';
foreach ($contents as $c){
    $span_content .= '<span>'.$c.'</span> ';
    $i++;
}
$result = $span_content;

上面的代码在正常情况下工作得很好,但有时 $paragraph 会包含一些 html 标签,例如
$paragraph = "This is an image: <img src='/img.jpeg' /> This is a <a href='/abc.htm'/>Link</a>'";

如何不将“单词”包装在 html 标签中,以便 htmnl 标签仍然有效,但将其他单词包装在跨度中?非常感谢!

最佳答案

一些 (*SKIP)(*FAIL) 机制?

<?php
$content = "This is an image: <img src='/img.jpeg' /> ";
$content .= "This is a <a href='/abc.htm'/>Link</a>";
$regex = '~<[^>]+>(*SKIP)(*FAIL)|\b\w+\b~';

$wrapped_content = preg_replace($regex, "<span>\\0</span>", $content);
echo $wrapped_content;

查看 ideone.comregex101.com 上的演示。

要省略 Link ,你可以去:
(?:<[^>]+>     # same pattern as above
|              # or
(?<=>)\w+(?=<) # lookarounds with a word
)
(*SKIP)(*FAIL) # all of these alternatives shall fail
|
(\b\w+\b)

请参阅 regex101.com 上的演示。

关于php - 如何用 PHP 将每个单词包装在 span 中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36999957/

10-11 10:53