0

I am working with PHP and WordPress right now, I need to basically run the below code to Replace text in $current_path with the text in $new_path if $current_path EXIST in $content

I would prefer to be able to iterate over an array instead of running this over and over like this, or any better method would be nice?

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

4 Answers 4

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

Or you can use a single array with strtr():

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

However, you seem to be doing something very generic. Maybe all you need is a regex?

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

Or maybe even just

$new_content = preg_replace('/(\w+)-(tag)/u', '\1/\2', $content);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

0

You can do that:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.