[英]Get words from string - skip html
我使用一個函數來獲取字符串的第一個“ x”字。 主要部分是:
preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
當單詞在html內時-示例:
<a href="/"><u>Linktext</u></a>
正則表達式將單詞“ linktext”視為一個單詞。 正則表達式應更改為跳過 html標記內的每個單詞。
這可能嗎?
使用XSL轉換。 我從相關答案( 如何從XML文檔中刪除所有文本 )中使用了模板:
$string = '<a href="/">Some text <u>Linktext</u> more text</a>';
$xslTemplate = '<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<!-- copy all nodes -->
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- clear attributes -->
<xsl:template match="@*">
<xsl:attribute name="{name()}" />
</xsl:template>
<!-- ignore text content of nodex -->
<xsl:template match="text()" />
</xsl:stylesheet>';
libxml_use_internal_errors(true);
$inputDom = new DOMDocument();
$inputDom->loadHTML($string);
$xslDom = new DOMDocument();
$xslDom->loadXML($xslTemplate);
$cp = new XSLTProcessor();
$cp->registerPHPFunctions();
$cp->importStylesheet($xslDom);
$transformedResult = $cp->transformToDoc($inputDom);
$transformedHtmlString = $transformedResult->saveXML($transformedResult->getElementsByTagName('body')->item(0));
$transformedHtmlString = str_replace('<body>','', $transformedHtmlString); //saveXml() method leaves automatically created body tag
$transformedHtmlString = str_replace('</body>','', $transformedHtmlString);
echo $transformedHtmlString;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.