简体   繁体   English

如何使用str_replace替换PHP中的多个字符串?

[英]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. 我试图使用str_replace()函数删除我不需要的字符串。 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. 在替换.mp4,.ogg,.webm时我没有问题。 But in replacing the clip_ together with the .mp4, etc etc has an incorrect result. 但是在用.mp4等替换clip_时,结果不正确。

clip_sample_data_2clip_

It appears you are misunderstanding how to use str_replace to replace multiple strings. 您似乎误解了如何使用str_replace替换多个字符串。 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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