Home > Article > Backend Development > How to replace src with regular php
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.
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 = '#<img(.+?)src\s*=\s*[\"|\']([^"|^\']+?)[\"|\']([^>]*?)>#'; $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('get_img_path')){ function get_img_path($img){ //当前环境 $env_info = getenv('APP_ENV'); switch ($env_info){ case 'local': $url = 'https://local.***.com/'.$img; break; case 'test': $url = 'https://test.***.com/'.$img; break; case 'production': $url = 'https://production.***.com/'.$img; break; default: $url = 'https://local.***.com/'.$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!