简体   繁体   中英

How to replace multiple strings in PHP using str_replace?

Hi guys I have an error with my code. I am trying to use the str_replace() function to remove the string I don't need. But I don't get my expected result. Here's my code:

Here's my sample data:

clip_sample_data.mp4
clip_sample_data.ogg
clip_sample_data.webm

Here's my function:

$video_data = array(
            'mp4_title'     =>  isset($columns['mp4_title']) ? str_replace(".mp4", "", pathFileNameExploder($columns['mp4_title'])) : '',
            'ogg_title'     =>  isset($columns['ogg_title']) ? str_replace(".ogg", "", pathFileNameExploder($columns['ogg_title'])) : '',
            'webM_title'    =>  isset($columns['webM_title']) ? str_replace(".webm", "", pathFileNameExploder($columns['webM_title'])) : '',
            'clip_mp4'      =>  isset($columns['clip_mp4_title']) ? str_replace(array(".mp4", ""), array("clip_", ""), pathFileNameExploder($columns['clip_mp4_title'])) : '',
            'clip_ogg'      =>  isset($columns['clip_ogg_title']) ? str_replace(array(".ogg", ""), array("clip_", ""), pathFileNameExploder($columns['clip_ogg_title'])) : '',
            'clip_webm'     =>  isset($columns['clip_webm_title']) ? str_replace(array(".mp4", ""), array("clip_", ""), pathFileNameExploder($columns['clip_webm_title'])) : '',
        );

In replacing the .mp4, .ogg, .webm I have no problem. But in replacing the clip_ together with the .mp4, etc etc has an incorrect result.

clip_sample_data_2clip_

It appears you are misunderstanding how to use str_replace to replace multiple strings. The first argument is an array of string you want to replace, and the second is another array of matching strings to replace them with.

You probably intended to do something like this.

str_replace(array(".mp4", "clip_"), array("", ""), "clip_sample_data.mp4")

Which will return the following string.

"sample_data"

And since you want to replace everything with just a blank string, this code can be reduced to this.

str_replace(array(".mp4", "clip_"), "", "clip_sample_data.mp4")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM