如何使用PHP在多页字符串中搜索HTML标记



是否可以使用strpos()搜索HTML标记?似乎产生了无效的结果。还尝试转换为htmlentities(),但仍然没有成功。如何正确搜索文本装饰,如:粗体、斜体和下划线?

示例:(演示)

/* HTML Tags to search for. */
$html_tags = array(
    'bold' => array(
        'before' => '<strong>',
        'after' => '</strong>'
    ),
    'italics' => array(
        'before' => '<em>',
        'after' => '</em>'
    ),
    'underline' => array(
        'before' => '<span style="text-decoration: underline;">',
        'after' => '</span>'
    )
);
/* Sample Strings... */
$html_test = array(
    'bold_with_html' => '<strong>Some string containing HTML tags.</strong>',
    'italics_with_html' => '<em>Some string containing HTML tags.</em>',
    'underline_with_html' => '<span style="text-decoration: underline;">Some string containing HTML tags.</span>',
    'without_html' => 'Some string containing no HTML tags.'
);
/* Check for HTML Tags. */
$results = array();
foreach($html_test as $key => $value){
    foreach($html_tags as $decoration => $html_tag){
        if(stripos($html_tag['before'], $value) !== false && strripos($html_tag['after'], $value) !== false){
            $results[$key][$decoration] = 'Located HTML: '.$decoration.'!';
        } else{
            $results[$key][$decoration] = 'No HTML located.';
        }
    }
}
print_r($results);

stripos的参数顺序错误,应该是干草堆,然后是针。。。

if(stripos($value,$html_tag['before']) !== false && strripos($value,$html_tag['after']) !== false){

为什么要使用RegEx?你最好的选择是DOM。

RegEx匹配除XHTML自包含标签之外的开放标签

最新更新