字符串位置在字符串中找到开头 div

String position find opening div in string

我尝试在此变量中找到包含 html

'<video' 字符串
$string="<video autoplay="autoplay" loop="" muted="" poster="" preload="auto" style="width: 354.09836065574px; height: 600px; max-height:600px;;display:block;margin:0 auto;"><source src="" type="video/mp4" /> <source src="" type="video/webm" />
<div class="badge-item-animated-img">&nbsp;</div> "

所以我使用:

if (strpos($string, '<video')){
   echo $string;
}

为什么这不起作用?

因为 strpos returns 标签的当前位置 'video',在你的例子中是 0。在 PHP 中,这与 false 相同。试试这个:

if (strpos($string, '<video') !== false){
     echo $string;
 }
$string='<video autoplay="autoplay" loop="" muted="" poster="" preload="auto" style="width: 354.09836065574px; height: 600px; max-height:600px;;display:block;margin:0 auto;"><source src="" type="video/mp4" /> <source src="" type="video/webm" />
    <div class="badge-item-animated-img"> </div> ';

if (strpos($string, '<video') !== false) {
    echo 'true';
}

请注意,!== false 的使用是故意的; strpos returns 针串在 haystack 串中开始的偏移量,或者布尔值 false 如果未找到针。由于 0 是一个有效的偏移量并且 0 是 "falsey",我们不能使用像 !strpos($a, 'are').

这样更简单的结构