PHP:需要这个带有通配符的字符串的确切位置


PHP: need this exact position of string with a wildcard

首先,感谢您阅读这篇文章并试图帮助我。我是php的新手,我有一些困难。

我在wordpress中创建了一个过滤器,它应该检查两个条件。过滤器运行良好,但我运行了一些问题。

这是我的代码

     function em_validate($result, $EM_Event){
        if ($_REQUEST['em_tickets'] > 1 && $_REQUEST['booking_comment'] == ''){
        $EM_Event->add_error('Something');  
        $result = false; 
     }
     return $result;
    }
add_filter('em_booking_validate','em_validate', 1, 2);

此筛选器工作正常,但是$_REQUEST['em_tickets'])的内容有点像

<p><strong>23</strong></p><ul><li>5</li></ul><p></p>

我需要获得<li> </li>中的值,以便使我的脚本正常工作。

if ($_REQUEST['em_tickets'] > 1 && $_REQUEST['booking_comment'] == ''){

感谢您阅读这篇文章并提出建议

建议二:也不能正常工作

function em_validate($result, $EM_Event){
$start = "<li>";
$end = "</li>";
    if (substr($_REQUEST['em_tickets'], $start, $end) > 1 && $_REQUEST['booking_comment'] == ''){
  $EM_Event->add_error($_REQUEST['em_tickets']); //('Something');

    $result = false;
 }
 return $result;
}
add_filter('em_booking_validate','em_validate', 1, 2);

如果你熟悉JavaScript上的DOM,你会发现这个解决方案非常简单,使用DOMDocument

<?php
    $html = "<p><strong>23</strong></p><ul><li>5</li><li>25</li></ul><p></p>";
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $liElements = $doc->getElementsByTagName('li');
    foreach($liElements as $li) {
        var_dump($li->textContent);
    }

不要将正则表达式用于html或xml之类的内容。相反,使用DOMDocument,因为它是为处理那些非规则结构而设计的。

$result = null;
$em_tickets = $_REQUEST['em_tickets']
$doc = new DOMDocument();
$doc->loadHtml($em_tickets);
$lis = $doc->getElementsByTagName('li');
if ($lis->length > 0) {
    $li = $lis[0];
    $result = $li->textContent;
}

错误检查可能会得到改进。

试试看:

$em_tickets = "<p><strong>23</strong></p><ul><li>5</li></ul><p></p>";
$start = "<li>";
$end = "</li>";
$id = substr($em_tickets, $start, $end);

输出:

 5

注:

使用offset并不等同于将substr($subject,$offset)传递到preg_match()来代替主题字符串,因为模式可以包含^、$或(?<=x)等断言。比较:

参考编号:http://php.net/manual/en/function.preg-match.php