Reputation:
I am trying to replace my custom short codes, but function str_replace return empty.
I have a fixed list of search.
$search = array(15) {
[0]=>
string(13) "{{user_name}}"
[1]=>
string(17) "{{ticket_number}}"
[2]=>
string(15) "{{ticket_link}}"
[3]=>
string(18) "{{ticket_subject}}"
[4]=>
string(22) "{{ticket_description}}"
}
$replace = array(1) {
[0]=>
string(23) "ticket with attachments"
}
$subject = string(20) "{{ticket_subject}}"
echo str_replace($search, $replace, trim($subject));
Why the result is empty?
Upvotes: 0
Views: 678
Reputation:
Make $replace
a string if you want all elements from $search
replaced with the same string.
From the documentation: "If search is an array and replace is a string, then this replacement string is used for every value of search."
<?php
$search = [
"{{user_name}}",
"{{ticket_number}}",
"{{ticket_link}}",
"{{ticket_subject}}",
"{{ticket_description}}",
];
$replace = "ticket with attachments";
$subject = "{{ticket_subject}}";
echo str_replace($search, $replace, $subject);
Edit: different approach using array:
<?php
$replacements = [
"{{user_name}}" => 'Roman',
"{{ticket_number}}" => 1234567890,
"{{ticket_link}}" => 'url.com',
"{{ticket_subject}}" => 'Hello World',
"{{ticket_description}}" => 'foo bar',
];
$search = array_keys($replacements);
$replace = array_values($replacements);
$subject = "Dear {{user_name}}, we received your ticket #{{ticket_number}} with subject {{ticket_subject}}({{ticket_description}}). As a reminder, {{user_name}}, please close your ticket #{{ticket_number}}";
echo str_replace($search, $replace, $subject);
will output:
Dear Roman, we received your ticket #1234567890 with subject Hello World(foo bar). As a reminder, Roman, please close your ticket #1234567890
Upvotes: 2
Reputation: 337
According to the PHP documentation:
If replace has fewer values than search, then an empty string is used for the rest of replacement values
Your search array has more values than your replace array.
(https://www.php.net/manual/en/function.str-replace.php)
Upvotes: 0