使用 html 标签搜索字符串

search string with html tags

我在 PHP 变量中有 html 内容,我想用它的标签搜索特定的字符串。

假设我的变量是

$var = "<html>Hi.. <strong>how</strong>are <u>you?</u></html>

现在我想在 $var 中搜索 how 然后它应该 return 我用它的标签所以我应该得到 how

如何使用 PHP 完成此操作?

如有任何帮助,我们将不胜感激。

使用正则表达式:

$search = 'how';
$var = "<html>Hi.. <strong>how</strong>are <u>you?</u></html>";
preg_match_all('/<[^>]+>'.$search.'<\/[^>]+>/',$var,$matches);
$found = $matches[0][0];
echo $found;

输出:

如何

要获取所有 how 字符串,包括带标签和不带标签的字符串,请将您的正则表达式更改为此(添加 OR | 运算符:

preg_match_all('/<[^>]+>'.$search.'<\/[^>]+>|\b'.$search.'\b/',$var,$matches);

您想要包含您的值的元素吗?您可以采用 xpath 方法:

<?php
$var = "<html>Hi.. <strong>how</strong>are <u>you?</u></html>";
$xml = simplexml_load_string($var);
$elements = $xml->xpath("//*[. = 'how']");
# looking for any value in the tree where the text equals 'how'
# giving back an array of found matches
print_r($elements);
?>

在此处查看 ideone.com 演示。

你确定你的问题吗??

如果您想知道您的搜索字符串是否在 $var 中,请试试这个。

<?php
$var = "<html>Hi.. <strong>how</strong>are <u>you?</u></html>";
$findme = "how";
$pos = strpos($var, $findme);
if($pos === false)
  echo $findme.", Not found.";
else
  echo $findme.", The string found";
?>