从 HTML 字符串中获取具有特定类和数据属性的 td 单元格的值[重复]

问题描述 投票:0回答:3

我正在尝试找到这样的子字符串:

// get needle for strpos
$someStringContainingHtmlTags = '<table><td class="size1of2 bold">Order no</td></div><td class="size1of2" data-template="productBestnr">64210</td></table>';

$re = '/<td class="size1of2" data-template="productBestnr">\d+<\/td>/';
preg_match($re, $someStringContainingHtmlTags , $matches);

$art = (string)$matches[0];

$needle = '<td class="size1of2" data-template="productBestnr">'.$art.'</td>';

// echos nothing
echo strpos($someStringContainingHtmlTags , $needle);

如果我用实际值替换 $art

64210
strpos
就可以了。

php
3个回答
1
投票

为了获得正确的

$art
值 (64210),您应该将
\d
放入一个组中:
$re = '/<td class="size1of2" data-template="productBestnr">(\d+)<\/td>/';


0
投票

正如@Sir McPotato 所说,你需要将表达放入群体中。

matches
的第二个元素将返回
64210

<?php
// get needle for strpos
$someStringContainingHtmlTags  = '<table><td class="size1of2 bold">Order no</td></div><td class="size1of2" data-template="productBestnr">64210</td></table>';

$re = '/<td class="size1of2" data-template="productBestnr">(\d+)<\/td>/';
preg_match($re, $someStringContainingHtmlTags , $matches);

$art = (string)$matches[1];

$needle = '<td class="size1of2" data-template="productBestnr">'.$art.'</td>';

// echos nothing
echo strpos($someStringContainingHtmlTags , $needle);

0
投票

检查一下,

$someStringContainingHtmlTags = '<table><td class="size1of2 bold">Order no</td></div><td class="size1of2" data-template="productBestnr">64210</td></table>';
$re = '/<td class="size1of2" data-template="productBestnr">\d+<\/td>/';
preg_match($re, $someStringContainingHtmlTags , $matches);
$art = (string)$matches[0];
// echos nothing
echo strpos($someStringContainingHtmlTags , $art);

你的$art实际上是你的针。你在针内添加了针。

一旦 echo $art 你就会得到它。

© www.soinside.com 2019 - 2024. All rights reserved.