Home > Backend Development > PHP Problem > How to perform string matching and replacement in php

How to perform string matching and replacement in php

coldplay.xixi
Release: 2023-03-06 12:56:02
Original
2660 people have browsed it

php字符串匹配替换的方法:执行一个正则表达式搜索并且使用一个回调进行替换,代码为【preg_replace_callback()return  preg_replace_callback('/\\{([\w\-\/]+)\\}/'】。

How to perform string matching and replacement in php

php字符串匹配替换的方法:

 <?php
    $templ = "{username}是个大{adj}比{end}";//测试字符串
    //对应数据
    $datas = [
        &#39;username&#39; => &#39;我&#39;,
        &#39;adj&#39; => &#39;帅&#39;,
        &#39;end&#39; => &#39;。&#39;,
    ];
    //不需要替换的字符串
    $noMatchs = [&#39;end&#39;];
    function render($datas = array(), $templ = &#39;&#39;, $noMatchs = array()) {
            //preg_replace_callback()
            //执行一个正则表达式搜索并且使用一个回调进行替换
            return  preg_replace_callback(&#39;/\\{([\w\-\/]+)\\}/&#39;, function ($matches) use ($datas, $noMatchs) {
                //$matches[1]返回如:username
                $name = $matches[1];
                if (in_array($name, $noMatchs)) {
                    //$mathches[0]返回如:{end}
                    return $matches[0];
                }
                return array_key_exists($name, $datas) ? $datas[$name] : &#39;&#39;;
            }, $templ);
        }
    var_dump(render($datas, $templ, $noMatchs));
    //输出结果为:&#39;我是个大帅比{end}&#39;
Copy after login

相关免费学习推荐:php编程(视频)

The above is the detailed content of How to perform string matching and replacement in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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