Have a string: $str = "Hello, {{first_name}} {{last_name}}!";
And variables $first, $last... in array
$trans = array("{{first_name}}" => $first, "{{last_name}}" => $last, "{{cart}}" => $crt1, "{{phone}}" => $phone, "{{adds}}" => $addr, "{{order_id}}" => $order_id);
How to replace {{first_name}}->$first, {{last_name}}->$last
Here what i did:
function replace_str($str, $trans)
{
$subj = strtr($str, $trans);
return $subj;
}
$cart = replace_str($str,$trans);
But strtr doesn't work with cyrillic (utf-8)
Your code is fine. strtr() supports multibyte strings, but the array form strtr(string, array) should be used. Example:
$str = "Hello {{first_name}}!";
$first_name = "мир.";
$trans = ['{{first_name}}' => $first_name];
echo strtr($str, $trans); // Hello мир.!
You can use str_replace with array_keys.
PHP Code:
<?php
$str = "Hello, {{first_name}} {{last_name}}!";
$first = "ХѠЦЧШЩЪЪІ";
$last = "ЬѢꙖѤЮѪ";
$crt1 = "";
$phone = "";
$addr = "";
$order_id = "";
$trans = array("{{first_name}}" => $first, "{{last_name}}" => $last, "{{cart}}" => $crt1, "{{phone}}" => $phone, "{{adds}}" => $addr, "{{order_id}}" => $order_id);
echo str_replace(array_keys($trans), array_values($trans), $str);
Check the output at: https://3v4l.org/0fCv3
Refer:
http://php.net/manual/en/function.str-replace.php
http://php.net/manual/en/function.array-keys.php
use str_replace(); , you can resolve your problem.
$str = "Hello, {{first_name}} {{last_name}}!";
$str1 = str_replace("{{first_name}}",$first,$str);
$str2 = str_replace("{{last_name}}",$last,$str1);
echo $str2;
First i have replaced {{first_name}} with $first in $str. Then I have replaces {{last_name}} with $last in $str1.
You can use str_replace() or str_ireplace() for case insensitive version.
Here example as your code,
str_replace(array_keys($trans), $trans, $str);
Related
How can I update this code :
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $array);
with the preg_replace_callback function?
Thanks.
preg_replace_callback() is very similar to preg_replace(), except parameter 2 is a callable function that takes $matches as a parameter. Don't forget to remove the /e modifier, since we aren't executing anything.
$array = array(
's:1:"test";',
's:2:"one more";',
);
$data = preg_replace_callback('!s:(\d+):"(.*?)";!', function($matches) {
$string = $matches[2];
$length = strlen($string);
return 's:' . $length . ':"' . $string . '";';
}, $array);
print_r($data);
// Array ( [0] => s:4:"test"; [1] => s:8:"one more"; )
i want to replace a char and want to put that character just after next char in php.
for example:
<?php
$exa = array("R" => "r", "A" => "a", "V" => "v", "I" => "i");
echo strtr("RAVI", $exa);
?> //displays "ravi" ok
i want to replace "V" with "v" and then want to put it after "I".
like this: "raiv"
I think this solution might interest you:
Function
function replaceAndMove($text, $replacements) {
$from = array_keys($replacements);
$to = array_values($replacements);
function fixFrom($s) {
return '/' . preg_quote($s, '/') . '(.|$)' . '/';
}
function fixTo($s) {
return '${1}' . $s;
}
$from_ready = array_map('fixFrom', $from);
$to_ready = array_map('fixTo', $to);
return preg_replace($from_ready, $to_ready, $text);
}
Test Case
$text = "abcdXefghXijklX----aFb~~~cMd";
$replacements = array(
'X' => 'x',
'F' => 'f',
'M' => 'm',
);
echo $text . '<br>';
echo replaceAndMove($text, $replacements);
Output
abcdXefghXijklX----aFb~~~cMd
abcdexfghixjkl-x---abf~~~cdm
Edit: Fixed problems with regex-special chars, such as . or ]
do the str_replace first, then use strlen, substr and the index of the character string to replace the last 2 spots if that is what you are trying to do. Because you can access a string like an array each characters $t[1] == e if the string was "test"
If you have a few "set" patterns you could just do this:
$find = array('RAVI',...,so on);
$replace = array('raiv',..., so on);
$input = 'RAVI';
echo str_replace($find, $replace, $input);
Just add more set pairs to the arrays for more replacements... If that's all you want.
Are you looking for something like this:
<?php
$string = "RAVIVL";
$replace_char = "v";
$string = strtolower($string);
$pos = array_keys(array_intersect(str_split($string),array($replace_char)));
foreach ($pos as $p) {
if (isset($string[$p+1])) {
$string[$p] = $string[$p+1];
$string[$p+1] = $replace_char;
}
}
echo $string;
?>
Swaps all occurrences o "v" with the following letter.
I'm having trouble finding a correct regex to achieve what I want.
I have a sentence like that :
Hi, my name is Stan, you are welcome, hello.
and I would like to transform it like that :
[hi|hello|welcome], my name is [stan|jack] you are [hi|hello|welcome] [hi|hello|welcome].
Right now my regex is half working, because somes words are not replaced, and those replaced are deleting some characters
Here is my test code
<?php
$test = 'Hi, my name is Stan, you are welcome, hello.';
$words = array(
array('hi', 'hello', 'welcome'),
array('stan', 'jack'),
);
$result = $test;
foreach ($words as $group) {
if (count($group) > 0) {
$replacement = '[' . implode('|', $group) . ']';
foreach ($group as $word) {
$result = preg_replace('#([^\[])' . $word . '([^\]])#i', $replacement, $result);
}
}
}
echo $test . '<br />' . $result;
Any help will be appreciated
The regex you are using is overcomplicated. You simply need to use a regex substitution using regular brackets ():
<?php
$test = 'Hi, my name is Stan, you are welcome, hello.';
$words = array(
array('hi', 'hello', 'welcome'),
array('stan', 'jack'),
);
$result = $test;
foreach ($words as $group) {
if (count($group) > 0) {
$imploded = implode('|', $group);
$replacement = "[$imploded]";
$search = "($imploded)";
$result = preg_replace("/$search/i", $replacement, $result);
}
}
echo $test . '<br />' . $result;
Your regular expression:
'#([^\[])' . $word . '([^\]])#i'
matches one character before and after $word as well. And as they do, they replace it. So your replacement string needs to reference these parts, too:
'$1' . $replacement . '$2'
Demo
preg_replace supports array as parameter. No need to iterate with a loop.
$s = array("/(hi|hello|welcome)/i", "/(stan|jack)/i");
$r = array("[hi|hello|welcome]", "[stan|jack]");
preg_replace($s, $r, $str);
or dynamically
$test = 'Hi, my name is Stan, you are welcome, hello.';
$s = array("hi|hello|welcome", "stan|jack");
$r = array_map(create_function('$a','return "[$a]";'), $s);
$s = array_map(create_function('$a','return "/($a)/i";'), $s);
echo preg_replace($s, $r, $str);
//[hi|hello|welcome], my name is [stan|jack], you are [hi|hello|welcome], [hi|hello|welcome].
My code:
$str = array(
'{$string1}' => 'anything2',
'{$string2}' => 'something1',
'{$string3}' => '...'
);
$final = "";
$text = $_POST['content'];
foreach( $str as $key => $val ) {
$final = str_replace($key, $val, $text);
}
My $text ofc. has {string1} , {string2} and {string3} itself, but it doesn't replace it with the values given in the array.
Why its not working?
This code does exactly what you need (without any extra loops):
$final = strtr($_POST['content'], $str);
use
$final = str_replace('{'.$key.'}', $val, $text);
Ref : http://php.net/manual/en/function.str-replace.php
Maybe the different enconding, try this:
$text = utf8_decode($_POST['content']);// or utf8_encode
before loop;
Good lucky!
Could you tell how to replace string by preg-replace (need regular expression):
/user/{parent_id}/{action}/step/1
At the equivalent values of an array:
array('parent_id'=>32, 'action'=>'some');
To make:
/user/32/some/step/1
Addition
This is a typical problem, so I probably will not know what the names of variables come
You can use str_replace
For example:
str_replace(array("{parent_id}", "{action}"), array(32, 'some'), "/user/{parent_id}/{action}/step/1");
$arr = array('parent_id'=>32, 'action'=>'some');
$out = str_replace(array_keys($arr),array_values($arr),$in);
no need for regexps!
Say you have:
$arr = array('parent_id'=>32, 'action'=>'some');
$in = '/usr/{parent_id}/{action}/step/1';
This will replace the braces:
function bracelize($str) {
return '{' . $str . '}';
}
$search = array_map('bracelize', array_keys($arr));
$out = str_replace($search, $arr, $in);
Or if you are using PHP >= 5.3 you can use lambdas:
$search = array_map(function ($v) { return '{'.$v.'}';}, array_keys($arr));
$out = str_replace($search, $arr, $in);
$s = '/user/{parent_id}/{action}/step/1';
$replacement = array('parent_id'=>32, 'action'=>'some');
$res = preg_replace(array('/\\{parent_id\\}/', '/\\{action\\}/'), $replacement, $s);
Of course, you could just as well use str_replace (in fact, you ought to).
<?php
$string = '/usr/{parent_id}/{action}/step/1';
$pattern = array('#{parent_id}#', '#{action}#');
$values = array('32', 'some');
echo preg_replace($pattern, $values, $string);
?>
If your problem is not more complicated than this, i would recommend changing preg_replace to str_replace though.
EDIT: I see you don't know the variable names in advance. In which case you could do something like this.
<?php
function wrap_in_brackets(&$item)
{
$item = '{' . $item . '}';
return true;
}
$string = '/usr/{parent_id}/{action}/step/1';
$variables = array('parent_id' => 32, 'action' => 'some');
$keys = array_keys($variables);
array_walk($keys, 'wrap_in_brackets');
echo str_replace($keys, array_values($variables), $string);
?>
Expanding on mvds' answer:
$in = 'user/{parent_id}/{action}/step/1';
$arr = array('{parent_id}' => 32, '{action}' => 'some');
$out = str_replace(array_keys($arr), $arr, $in);
Or:
$in = 'user/{parent_id}/{action}/step/1';
$arr = array('parent_id' => 32, 'action' => 'some');
$arr[] = '';
$find = array_merge(array_keys($arr), array('{', '}'));
$out = str_replace($find, $arr, $in);