str_replace doesn't work with foreach - php

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!

Related

Convert a string to an array with a key

I have a string like this:
<enq fiscal="no" lastcommanderror="no" intransaction="no" lasttransactioncorrect="yes" />
I want to convert the above string into an array, and the output has to be this:
array(
['fiskal'] => "no",
['lastcommanderror'] => "no",
['intransaction'] => "no",
['lasttransactioncorrect'] => "yes"
)
You can use SimpleXMLElement:
$xmlString = '<enq fiscal="no" lastcommanderror="no" intransaction="no" lasttransactioncorrect="yes" />';
$array = ((array)(new SimpleXMLElement($xmlString)))["#attributes"];
var_dump($array);
You could make the string a json by replacing some characters then json_decode it.
$str = str_replace(['<enq ', ' />', '=', ' '], ['{"', '}', '":', ',"'], $str);
$arr = json_decode($str, true);
You can try this:
$string = '<enq fiscal="no" lastcommanderror="no" intransaction="no"
lasttransactioncorrect="yes" />';
// remove the <enq /> and whitespaces
$string = trim(ltrim(rtrim($string, '/>'), '<enq'));
$finalArray = [];
foreach (explode(' ', $string) as $value) {
$elements = explode('=', $value);
$finalArray[$elements[0]] = $elements[1];
}

Replace {{word}} in string

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

str_replace() doesn't work using "(" and "[" PHP

This is my simple code function in php
function replaceCharact($input,$action){
$output_1 = str_replace('(', "%11%", $input);
$output_2 = str_replace(')', '%12%', $output_1);
$output_3 = str_replace('[', '%13%', $output_2);
$output_4 = str_replace(']', '%14%', $output_3);
$output_5 = str_replace('"', '%15%', $output_4);
$output_6 = str_replace('/', '%16%', $output_5);
$output_7 = str_replace('"\"', '%17%', $output_6);
$output_8 = str_replace('!', '%18%', $output_7);
$output_9 = str_replace('<', '%19%', $output_8);
$output_10 = str_replace('>', '%20%', $output_9);
return $output_10;
}
Only the "!"($output_8) change to %19%. The others output display nothing. Can you help me with this?
To simplify mass replacements using an array, try this...
$replacement = array(
'(' => "%11%",
')' => '%12%',
'[' => '%13%',
']' => '%14%'
// etc etc
);
$string = str_replace( array_keys( $replacement ), $replacement, $string );
https://3v4l.org/kmXZp

Replace everything from beginning of line to equal sign

For a content with the format:
KEY=VALUE
like:
LISTEN=I am listening.
I need to do some replacing using regex. I want this regular expression to replace anything before the = with $key (making it have to be from beginning of line so a key like 'EN' wont replace a key like "TOKEN".
Here's what I'm using, but it doesn't seem to work:
$content = preg_replace('~^'.$key.'\s?=[^\n$]+~iu',$newKey,$content);
$content = "foo=one\n"
. "bar=two\n"
. "baz=three\n";
$keys = array(
'foo' => 'newFoo',
'bar' => 'newBar',
'baz' => 'newBaz',
);
foreach ( $keys as $oldKey => $newKey ) {
$oldKey = preg_quote($oldKey, '#');
$content = preg_replace("#^{$oldKey}( ?=)#m", "{$newKey}\\1", $content);
}
echo $content;
Output:
newFoo=one
newBar=two
newBaz=three
$str = 'LISTEN=I am listening.';
$new_key = 'ÉCOUTER';
echo preg_replace('/^[^=]*=/', $new_key . '=', $str);
If I understood your question well, you need to switch the multi-line mode on using m modifier.
$content = preg_replace('/^'.preg_quote($key, '/').'(?=\s?=)/ium', $newKey, $content);
By the way I do recommend to escape the $key using preg_quote to avoid unexpected results.
So if the source content is this:
KEY1=VALUE1
HELLO=WORLD
KEY3=VALUE3
The result will be this (if $key=HELLO and $newKey=BYE):
KEY1=VALUE1
BYE=WORLD
KEY3=VALUE3
This should do the trick.
\A is the start of a line, and the parentheses is for grouping things to keep/replace.
$new_content = preg_replace("/\A(.*)(=.*)/", "$key$2", $content);
$content = 'LISTEN=I am listening.';
$key = 'LISTEN';
$newKey = 'NEW';
$content = preg_replace('~^'.$key.'(\s?=)~iu',$newKey.'$1',$content);
echo $content;
output is NEW=I am listening.
But is does not change on a partial match
$content = 'LISTEN=I am listening.';
$key = 'TEN';
$new_key = 'NEW';
$content = preg_replace('~^'.$key.'(\s?=)~iu',$newKey.'$1',$content);
echo $content;
Output is LISTEN=I am listening.

Could you tell how to replace by regular expression

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

Categories