Home >Backend Development >PHP Tutorial >正则表达式 - PHP foreach array return 正则式的问题

正则表达式 - PHP foreach array return 正则式的问题

WBOY
WBOYOriginal
2016-06-06 20:35:521023browse

<code>$a1 = '/\{[A-Z]*\}/';

$a2 = array(
'{DOMEA} = 'AAAAAA';
'{DOMEB} = 'BBBBBBB';
)

$a3 = return('
    <h1>title</h1>
    {DOMEA}
    <hr>
    {DOMEB}
');
$b1 = preg_replace($a1,$a2,$a3);
</code>

怎么才实现$a2自动匹配$a3里对应的内容呢?
满脑子全是浆糊,实在想不出来,用foreach试了半天了也没弄出来,不知那位路过的PHP大大能给解解……

回复内容:

<code>$a1 = '/\{[A-Z]*\}/';

$a2 = array(
'{DOMEA} = 'AAAAAA';
'{DOMEB} = 'BBBBBBB';
)

$a3 = return('
    <h1>title</h1>
    {DOMEA}
    <hr>
    {DOMEB}
');
$b1 = preg_replace($a1,$a2,$a3);
</code>

怎么才实现$a2自动匹配$a3里对应的内容呢?
满脑子全是浆糊,实在想不出来,用foreach试了半天了也没弄出来,不知那位路过的PHP大大能给解解……

<code><?php //http://3v4l.org/SHdjA
$a1 = '/\{[A-Z]*\}/';
$a2 = array(
'{DOMEA}'=>'AAAAAA',
'{DOMEB}'=>'BBBBBBB'
);
$a3 = '
    <h1>title</h1>
    {DOMEA}
    <hr>
    {DOMEB}
';
echo preg_replace_callback($a1, function($matches) use($a2) {
    return $a2[$matches[0]];
}, $a3);
?>
</code>

http://3v4l.org/KudfG

因为这根本不是什么正则,只是最普通的str_replace罢了……

<code>php</code><code>$a2 = array(
'{DOMEA}' => 'AAAAAA',
'{DOMEB}' => 'BBBBBBB',
);

$a3 = '


<h1>title</h1>


    {DOMEA}
    <hr>
    {DOMEB}
';

echo str_replace(array_keys($a2), array_values($a2), $a3);
</code>

<code>php</code><code><br>$a2 = array(
'{DOMEA}' => 'AAAAAA',
'{DOMEB}' => 'BBBBBBB',
);

$a3 = '


<h1>title</h1>


    {DOMEA}
    <hr>
    {DOMEB}
';
echo strtr($a3,$a2);
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn