gpt4 book ai didi

php - 您如何自定义格式化 html 标记 MySQL 字段中的第一个单词/字符?

转载 作者:行者123 更新时间:2023-12-02 04:20:30 26 4
gpt4 key购买 nike

我做了以下用于简单文本字段的操作:

$field = "How are you doing?";
$arr = explode(' ',trim($field));
$first_word = $arr[0];
$balance = strstr("$field"," ");

它不起作用,因为该字段包含 html 标记,可能是图像、视频、div、div、段落等,导致 html 中的所有文本都与文本混合在一起。

我可能会使用 strip_tags 去除 html,然后获取第一个词并重新格式化它,但随后我将不得不弄清楚如何将 html 添加回数据。我想知道是否有为此目的准备好的 php 或自定义函数。

最佳答案

您可以使用 DOMDocument解析 HTML,修改内容,并将其另存为 HTML。此外,查找单词并不总是像使用空格分隔符那么简单,因为并非所有语言都用空格分隔单词,而且并非所有单词都必须用空格分隔。例如:mother-in-law 根据您如何定义,这可以被视为一个词或 3 个。另外,像pancake这样的东西,你认为这是一两个词吗(pancake)?一种简单的解决方案是使用 IntlBreakIterator::createWordInstance实现 Unicode Standard for text segmentation 的类又名 UAX #29

以下是您可能如何实现此功能的示例:

$html = <<<'HTML'
<div>some sample text here</div>
HTML;

/* Let's extend DOMDocument to include a walk method that can traverse the entire DOM tree */
class MyDOMDocument extends DOMDocument {
public function walk(DOMNode $node, $skipParent = false) {
if (!$skipParent) {
yield $node;
}
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $n) {
yield from $this->walk($n);
}
}
}
}

$dom = new MyDOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

// Let's traverse the DOMTree to find the first text node
foreach ($dom->walk($dom->childNodes->item(0)) as $node) {
if ($node->nodeName === "#text") {
break;
}
}

// Extract the first word from that text node
$iterator = IntlBreakIterator::createWordInstance();
$iterator->setText($node->nodeValue); // set the text in the word iterator
$it = $iterator->getPartsIterator(IntlPartsIterator::KEY_RIGHT);
foreach ($it as $offset => $word) {
break;
}

// You can do whatever you want to $word here
$word .= "s"; // I'm going to append the letter s

// Replace the text node with the modification
$unmodifiedString = substr($node->nodeValue, $offset);
$modifiedString = $word . $unmodifiedString;
$oldNode = $node; // Keep a copy of the old node for reference
$node->nodeValue = $modifiedString;

// Replace the node back into the DOM tree
$node->parentNode->replaceChild($node, $oldNode);

// Save the HTML
$newHTML = $dom->saveHTML();

echo $newHTML;

输出

<div>somes sample text here</div>

关于php - 您如何自定义格式化 html 标记 MySQL 字段中的第一个单词/字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60235149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com