2013-04-29 78 views
0

我用PHP和WordPress现在的工作,我需要基本运行下面的代码在$current_path与文本$new_path替换文本如果$current_path存在$content做多个搜索并替换PHP字符串?

我宁愿能够遍历数组而不是像这样一遍又一遍地运行,或者更好的方法会更好吗?

$content = 'www.domain.com/news-tag/newstaghere' 

$current_path = 'test-tag'; 
$new_path = 'test/tag'; 
$content = str_replace($current_path, $new_path, $content); 

$current_path = 'news-tag'; 
$new_path = 'news/tag'; 
$content = str_replace($current_path, $new_path, $content); 

$current_path = 'ppc-tag'; 
$new_path = 'ppc/tag'; 
$content = str_replace($current_path, $new_path, $content); 
+0

检查:使用数组http://php.net/manual/en/function.str- replace.php – 2013-04-29 01:09:15

回答

2

str_replace() accepts array arguments

$current_paths = array('test-tag','news-tag','ppc-tag'); 
$new_paths = array('test/tag','news/tag','ppc/tag'); 
$new_content = str_replace($current_paths, $new_paths, $content); 

或者你可以使用与strtr()一个数组:

$path_map = array('test-tag'=>'test/tag', 'news-tag'=>'news/tag', 'ppc-tag'=>'ppc/tag'); 
$new_content = strtr($content, $path_map); 

但是,你似乎在做一件很普通的。也许你需要的只是一个正则表达式?

$new_content = preg_replace('/(test|news|ppc)-(tag)/u', '\1/\2', $content); 

,或者甚至只是

$new_content = preg_replace('/(\w+)-(tag)/u', '\1/\2', $content); 
2
$content = 'www.domain.com/news-tag/newstaghere' 

$current_paths = array('test-tag','news-tag','ppc-tag'); 
$new_paths = array('test/tag','news/tag','ppc/tag'; 
$content = str_replace($current_paths, $new_paths, $content); 
0

你可以这样做:

$content = 'www.domain.com/news-tag/newstaghere'; 
$content = preg_replace('~www\.domain\.com/\w++\K-(?=tag/)~', '/', $content);