preg_match_all empty matches


preg_match_all empty matches

我想匹配两个美元符号之间的任何字母和下划线,并获得匹配结果。

示例:

我得到<a href="$url$">foo</a>,我想要url$url$

我试过以下两种模式

$pattern = "/'$([a-z'_]*)'$/i";
$pattern = "/'$(.*)'$/i"; // well, that's actually not what I want.
preg_match_all($pattern, $line, $matches, PREG_PATTERN_ORDER);

好吧,这应该有效——至少它在regex101上有效。但当我在应用程序中测试它时,它不会。我只得到空的测试结果

array(2) { [0]=> array(2) { [0]=> string(0) "" [1]=> string(0) "" } [1]=> array(2) { [0]=> string(0) "" [1]=> string(0) "" } } 
// ...

有什么想法吗?

这是我用来测试它的示例文本(我每行测试一次)

<li>
    <div class="parent">
        <a href="$application_url$">
            <img preview_image src="$thumbnail$">
            <div class="battle_tag">$btag$</div>
            <div class="class_spec">$spec_one$  /  $spec_two$ $class$</div>
            <div class="item_lvl">ilvl $ilvl$</div>
            <div class="date">$obtained$</div>
        </a>
    </div>
</li>

由于我对PHP不是很熟悉,所以我会发布我如何阅读的代码,并获得实际的字符串。也许我在这里已经做错了什么。

$file = file($filename);
for($i=0; $i<count($file); $i++){
    $line = $file[$i];
    preg_match_all("/'$([a-z]*)'$/i", $line, $matches);
    var_dump($matches);
    echo "<br/>";
}

在正则表达式周围使用单引号:

preg_match_all( '/'$([a-z_]*)'$/i', $line, $matches );

单引号使PHP脱离变量插值模式。通常,在双引号字符串中转义'$就足够了,但当该双引号字符串是正则表达式时,显然就不够了。