正则表达式写在“空变量”和“非空变量”上


regex writes on "empty variable" & "not empty variable"

我正在探索正则表达式。我所有的正则表达式都在使用反复试验来工作。我对为空变量编写感到非常困惑。

我有这个正则表达式:

<[^>]*id='"test3'"(.*)value='"(.*?)'"[^>]*>
<input name="token" type="text" id="test3" value="valueA">

哪个搜索 id="test3" 并在值="值 A" 上写 a。 是的,它"有效",但我的问题是,如果 value=" 为空,它就不会。我对匹配标签非常非常困惑。

就像我用这个标签执行上面的正则表达式一样

<input name="token" type="text" id="test3" value=""> 

前任:

.PHP:

<?php
$html = file_get_contents('test.html');
$data['test1'] = 'TOKEN 1';
$data['test2'] = 'TOKEN 2';
foreach ($data as $id => $value)
{
    if(preg_match('%<[^>]*id='"'.$id.''"(.*)value='"(.*?)'"[^>]*>%', $html, $match))
    {
        $html = str_replace($match[2], $value, $html);
    }
}
echo $html;
?>

.HTML:

<input name="token1" type="text" id="test1" value="" />
<input name="token2" type="text" id="test2" value="B" />
</body>
</html>

期望输出:

TOKEN 1

TOKEN 2

它不会在空值="中写入任何变量 请帮我匹配?

我包含一个指向我的正则表达式的测试链接

试试吧!

这个问题有一个很好的答案,但我对匹配真的很困惑

匹配

如果要使用正则表达式执行替换,则必须使用 preg_replace() 函数:

$html = preg_replace('/<[^>]*?'bid="test3".*?'svalue="'K[^"]*(?="[^>]*>)/is',
                     'A', $html);

图案详情:

<[^>]*?'bid="test3" 
.*?                #  I use a lazy quantifier to avoid to match
                   # the last "value" attribute of the file
'svalue="          #  The space prevent you to match an
                   # hypotetic "abcdvalue" attribute
'K                 #  remove all that have been matched before from 
                   # the match result
[^"]*              #  all characters that are not a "
(?="[^>]*>)        #  a lookahead to check the end of the tag.
                   # it's only a check, the subpattern inside 
                   # is not in the match result too

最后的s修饰符用于点模式(.也可以匹配换行符)

要将其与阵列一起使用,您只需执行以下操作:

foreach ($data as $id=>$value) {
    $html = preg_replace('/<[^>]*?'bid="' . $id . '".*?'svalue="'K[^"]*(?="[^>]*>)/is',
                         $value, $html);
}
preg_replace('/<[^>]*'bid='"test3'"[^>]*'bvalue='"'K[^'"]*/', $value, $html);

在此处查看演示。


更新(基于OP的评论)

if (preg_match('/(<[^>]*'bid='"test3'"[^>]*'bvalue='")([^'"]*)/', $html, $match))
{
  $html = str_replace($match[1].$match[2], $match[1].$value, $html);    
}

在此处查看演示。

使用此正则表达式:

<[^>]*id='"test3'"(.*)(value='".*?'")[^>]*>

然后在代码中执行以下操作:

$html = str_replace($match[2], 'value="'.$value.'"', $html);

检查一下 regex101.com:http://regex101.com/r/qF9yH4