Home  >  Article  >  Backend Development  >  How to replace src with regular php

How to replace src with regular php

藏色散人
藏色散人Original
2022-10-25 10:28:301166browse

How to replace src with php regularity: 1. Open the corresponding PHP file; 2. Implement it through the "if(!function_exists('get_img_path')){function get_img_path($img){...}" method Get the image path according to different environments; 3. Use the "htmlspecialchars_decode" method to display the rich text editor content on the page.

How to replace src with regular php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

php How to replace src with regular expression?

PHP - Regularly matches the content of the article image tag src and replaces it

The image edited in the back-end rich text editor is displayed in various terminals

Because Not on the same server, the image access path is different

At this time, batch matching and replacement is required

//$info->content 是接口中返回文章的内容
    $preg = &#39;#<img(.+?)src\s*=\s*[\"|\&#39;]([^"|^\&#39;]+?)[\"|\&#39;]([^>]*?)>#&#39;;
        $info->content = preg_replace_callback($preg,function ($matches){
            $replace = get_img_path($matches[2]);//要替换的src
            return "<img{$matches[1]}src=\"$replace\"{$matches[3]}>";
        }, $info->content);

get_img_path() function obtains the image path according to different environments

if(!function_exists(&#39;get_img_path&#39;)){
    function get_img_path($img){
        //当前环境
        $env_info  = getenv(&#39;APP_ENV&#39;);
        switch ($env_info){
            case &#39;local&#39;:
                $url = &#39;https://local.***.com/&#39;.$img;
                break;
            case &#39;test&#39;:
                $url = &#39;https://test.***.com/&#39;.$img;
                break;
            case &#39;production&#39;:
                $url = &#39;https://production.***.com/&#39;.$img;
                break;
            default:
                $url = &#39;https://local.***.com/&#39;.$img;
                break;
        }
        return $url;
    }
}

Display on the page Rich text editor content

 <?php echo htmlspecialchars_decode($info->content);?>

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to replace src with regular php. For more information, please follow other related articles on the PHP Chinese website!

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