Home > Backend Development > PHP Tutorial > preg_replace - How to parse hidden variables in variables in php?

preg_replace - How to parse hidden variables in variables in php?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-02 13:34:01
Original
1040 people have browsed it

<code>$a = " #0 and #1 or (#0)";
$items = array(
    "a>1",
    "b>0"
);
$str = preg_replace("/#(\w+)/","\$items[$1]",$a);
echo $str;</code>
Copy after login
Copy after login

输出结果: $items[0] and $items[1] or ($items[0])

怎么才能让输出结果是:a>1 and b>0 or (a>1)?
请各位大神帮忙看一下,谢谢!

回复内容:

<code>$a = " #0 and #1 or (#0)";
$items = array(
    "a>1",
    "b>0"
);
$str = preg_replace("/#(\w+)/","\$items[$1]",$a);
echo $str;</code>
Copy after login
Copy after login

输出结果: $items[0] and $items[1] or ($items[0])

怎么才能让输出结果是:a>1 and b>0 or (a>1)?
请各位大神帮忙看一下,谢谢!

正则

<code>$items = [
    'a > 1',
    'b > 0',
    'abc' => 'c > 1'
];
$subject = '#0 and #1 or (#0) and #abc #nooo';
echo preg_replace_callback('/#([a-z0-9_]+)/i', function($v) use ($items){
    return isset($items[$v[1]]) ? $items[$v[1]] : $v[0];
}, $subject);</code>
Copy after login
<code>a > 1 and b > 0 or (a > 1) and c > 1 #nooo</code>
Copy after login
Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template