Forum Moderators: coopster

Message Too Old, No Replies

Implode inside str replace

Not working

         

Sub_Seven

3:54 pm on Feb 25, 2016 (gmt 0)

10+ Year Member



Hello people,

Anyone could be so kind to explain to me why this is not working

This line:
$search = "'{{" . implode("}}', '{{", $content_element_id_array) . "}}'";


Produces this string:
'{{1}}', '{{2}}'


This str_replace works fine:
str_replace(['{{1}}', '{{2}}'], ['THIS BE 1', 'THIS BE 2'], $cms_section_content_data->content);


But when I try to replace the search string for the variable $search, it doesn't work:
str_replace([$search], ['THIS BE 1', 'THIS BE 2'], $cms_section_content_data->content);


Can someone tell me where's the problem here?

Thanks so much!

whitespace

4:51 pm on Feb 25, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



Because $search is a string and [$search] is a single element array containing your string. Whereas in your first str_replace() which works, ['{{1}}', '{{2}}'] is an array of 2 string elements: '{{1}}' and '{{2}}'. [$search] is equivalent to ["'{{1}}', '{{2}}'"].

$search should be an array, not a string. And then just pass $search as the first argument to str_replace(), not [$search].

whitespace

6:02 pm on Feb 25, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



For example, you could do this with array_map() and an anonymous function, rather than implode():


$search = array_map(
function($value) {
return '{{'.$value.'}}';
}, $content_element_id_array);



print_r($search);



Array (
[0] => {{1}}
[1] => {{2}}
)

Sub_Seven

7:56 pm on Feb 25, 2016 (gmt 0)

10+ Year Member



It works great :)

Thanks so much whitespace!