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

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

WBOY
Release: 2016-06-06 20:35:52
Original
1048 people have browsed it

<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>
Copy after login
Copy after login

怎么才实现$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>
Copy after login
Copy after login

怎么才实现$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>
Copy after login

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>
Copy after login

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

$a3 = '


<h1>title</h1>


    {DOMEA}
    <hr>
    {DOMEB}
';
echo strtr($a3,$a2);
</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template