0

我现在正在使用 PHP 和 WordPress,我基本上需要运行下面的代码来用if EXIST in 中$current_path的文本替换文本$new_path$current_path$content

我希望能够迭代一个数组,而不是像这样一遍又一遍地运行它,或者任何更好的方法会很好?

$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);
4

4 回答 4

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);
于 2013-04-29T01:10:38.277 回答
2

str_replace()接受数组参数

$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);
于 2013-04-29T01:16:43.703 回答
0

Array arguments can be provided for the str_replace function, as noted on the following PHP.net page:
http://php.net/manual/en/function.str-replace.php

Please see "Example #2" on the page linked above for details.

于 2013-04-29T01:10:08.450 回答
0

你可以这样做:

$content = 'www.domain.com/news-tag/newstaghere';
$content = preg_replace('~www\.domain\.com/\w++\K-(?=tag/)~', '/', $content);
于 2013-04-29T01:20:05.920 回答