在PHP中查找并从String中提取匹配值

Abd*_*rai 0 php regex

我有一个如下文字

$str = '<div>
           <div id="priceRangeWrapper">
              <div id="priceSlider" min="0" max="0"></div>
           </div>
        </div>';
Run Code Online (Sandbox Code Playgroud)

1)首先,我想<div id="priceSlider" min="0" max="0"></div>从上面的字符串中获取最小值和最大值是随机的位置.类似于Php的strpos()函数,它返回int的位置

 $pos = strpos($str, '<div id="priceSlider" min="0" max="0"></div>');
 //but min and max values are random. I don't know what can be they
Run Code Online (Sandbox Code Playgroud)

2)我想从上面的文本中获取最小值最大值.如何在PHP中使用/不使用regex获取这两个值?

nic*_*ckb 5

不要使用正则表达式来解析HTML.相反,这是DOMDocument的一个例子.

$doc = new DOMDocument();
$doc->loadHTML($str); // Load the HTML string from your post

$xpath = new DOMXPath($doc);
$node = $xpath->query('//div[@id="priceSlider"]')->item(0); // Get the <div>

// Print out the min and max attribute values
echo $node->getAttribute('min') . " " . $node->getAttribute('max');
Run Code Online (Sandbox Code Playgroud)

你可以看到它在这里工作.

  • @AbdulJabbarWebBestow实际上,DOMDocument可能是处理HTML页面的最佳解决方案.这几乎是标准的做法. (4认同)