提问人:user1049961 提问时间:5/29/2023 更新时间:5/29/2023 访问量:28
PHP - 在 x 字后插入文本,但不在标签内插入文本
PHP - Insert text after x words, but not inside tag
问:
我有以下字符串:
Lorem ipsum <strong>dolor sit amet</strong>Aenean fermentum risus <strong><a href="https://google.com">id tortor.</a></strong> <strong>Suspendisse nisl.</strong> dictum at dui. Aenean id metus <strong><a href="https://google.com"> id velit</a> ullamcorper pulvinar</strong>. Neque porro quisquam es qui dolorem ipsum.
我需要在第 10 个单词之后插入文本,但前提是它不在 html 标签内。为了更清楚,我需要计算单词(甚至是标签内的单词),找到第 10 个单词,如果在标签内,请继续到外部标签的末尾并插入该位置。read more
read more
简单显然不适用于这种情况。有人可以帮忙吗?explode by space
答:
0赞
Kadir Türkoğlu
5/29/2023
#1
运行此代码时,您可以看到给定示例文本的修改版本,并在第 10 个单词后添加了“新文本”。
<?php
function insertAfterTenWords($text, $insertion) {
$words = preg_split('/\s+/', $text);
$wordCount = count($words);
$openTags = [];
$newText = '';
for ($i = 0; $i < $wordCount; $i++) {
$word = $words[$i];
if (strpos($word, '<') !== false) {
$openTags[] = substr($word, strpos($word, '<'));
$newText .= $word . ' ';
} else if (strpos($word, '>') !== false) {
$lastTag = array_pop($openTags);
$newText .= $word . ' ';
while ($lastTag != substr($word, strpos($word, '<'))) {
$word = $words[++$i];
$newText .= $word . ' ';
}
} else {
$newText .= $word . ' ';
}
if ($i == 9 && count($openTags) == 0) {
$newText .= $insertion . ' ';
}
}
while (count($openTags) > 0) {
$newText .= array_pop($openTags);
}
return trim($newText);
}
$text = 'Lorem ipsum <strong>dolor sit amet</strong>Aenean fermentum risus <strong><a href="https://google.com">id tortor.</a></strong> <strong>Suspendisse nisl.</strong> dictum at dui. Aenean id metus <strong><a href="https://google.com"> id velit</a> ullamcorper pulvinar</strong>. Neque porro quisquam es qui dolorem ipsum.';
$insertion = '<a href="#">new text</a>';
echo insertAfterTenWords($text, $insertion);
?>
评论
<html>