html中的子字符串

时间:2012-04-18 13:40:03

标签: php substring

<p style="color:red;font-size:12px;">This economy car is great value for money and with the added benefit of air conditioning is ideal for couples and small families. A ?500 excess applies which can be waived to NIL for only <b>5.00</b> per day</p>

使用以下2种方法

substr($mytext,0,25);

 $s = html_entity_decode($mytext);
 $sub = substr($s, 0, 50);�

需要获得前50个字符......任何人请帮助

感谢

2 个答案:

答案 0 :(得分:2)

您需要一个HTML Paser,找到并读出纯文本并选择子字符串,这里是DOMXpath的示例:

$doc = DOMDocument::loadHTML($html);
$xp = new DOMXPath($doc);
$chars50 = $xp->evaluate('substring(normalize-space(//body),1,50)');

Demo

  

string(50)"This economy car is great value for money and with"

请注意,您将在此处获得UTF-8编码字符串。您也可以使用正则表达式(可能help you to cut at words)自行执行此操作,例如:

# load text from HTML
$text = DOMDocument::loadHTML($html)->getElementsByTagName('body')->item(0)->nodeValue;

# normalize HTML whitspace
$text = trim(preg_replace('/\s{1,}/u', ' ', $text));

# obtain the substring (here: UTF-8 safe operation, see as well mb_substr)
$chars50 = preg_replace('/^(.{0,50}).*$/u', '$1', $text);

Demo

如果您使用strip_tags而不是HTML解析器,则需要自行处理不同的编码。由于原始字符串已经有一个问号标记,表示unicode替换字符,我说你已经处理过borked数据,所以最好使用重新呈现的库,如DOMDocument而不是strip_tags不安全(请参阅PHP手册页上的警告)。

答案 1 :(得分:1)

希望这有效......试试

echo (substr(strip_tags($mytext), 0, 25));

http://www.ideone.com/6TgJX