[英]How to remove specific html tag and it's content from string in php
I have some string values like this example,我有一些像这个例子这样的字符串值,
1) '7-6 6 , 7-6 5 ' 2) '6 10 -7, 6-0, 6-2' 1) '7-6 6 , 7-6 5 ' 2) '6 10 -7, 6-0, 6-2'
I want below output, 1) '7-6, 7-6' 2) '6-7, 6-0, 6-2'我想要下面的输出,1) '7-6, 7-6' 2) '6-7, 6-0, 6-2'
I have written below php code which is not working properly,我在下面写了无法正常工作的 php 代码,
$score = '7-6<sup>6</sup>, 7-6<sup>5</sup>';
// $score ='6<sup>10</sup>-7, 6-0, 6-2';
while(strpos($score, '<sup>') !== false) {
$tag_start = strpos($score, '<sup>');
$tag_end = strpos($score, '</sup>') + 5;
$sub_str = substr($score, $tag_start, $tag_end);
$score = str_replace($sub_str, '', $score);
$score = str_replace(' ', '', $score);
}
echo $score;
One reliable way to do that, is to use a XML parser and its methods, eg SimpleXML .一种可靠的方法是使用XML 解析器及其方法,例如SimpleXML 。 The advantage over string replacing with fixed string lengths (
strpos(…) + 5
) or using regular expressions, is that you really can find all occurrences of a specified element, even if it bears attributes.与使用固定字符串长度(
strpos(…) + 5
)或使用正则表达式替换字符串相比的优势在于,您确实可以找到指定元素的所有出现,即使它带有属性。
<?php
$score = '7-6<sup>6</sup>, 7-6<sup>5</sup>, 6<sup>10</sup>-7, 6-0, 6-2';
/* Add a temporary wrapper element, so that any string input may be parsed as valid XML */
$xml = new SimpleXMLElement(sprintf('<html>%s</html>', $score));
/* Find the elements to be deleted using XPATH */
foreach ($xml->xpath('sup') as $sup) {
/* Remove this node using unset() */
unset($sup[0]);
}
/* Remove the temporary wrapper and the XML header, which is printed by asXML() */
$xmlOutput = trim(str_replace(['<?xml version="1.0"?>', '<html>', '</html>'], '', $xml->asXML()));
var_dump($xmlOutput);
See also https://en.wikipedia.org/wiki/XPath另见https://en.wikipedia.org/wiki/XPath
Another option would be to use strip_tags()
and list all allowed tags in the second attribute.另一种选择是使用
strip_tags()
并在第二个属性中列出所有允许的标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.