Search and replace multiple values with multiple/different values in PHP5? - php

Is there an inbuilt PHP function to replace multiple values inside a string with an array that dictates exactly what is replaced with what?
For example:
$searchreplace_array = Array('blah' => 'bleh', 'blarh' => 'blerh');
$string = 'blah blarh bleh bleh blarh';
And the resulting would be: 'bleh blerh bleh bleh blerh'.

You are looking for str_replace().
$string = 'blah blarh bleh bleh blarh';
$result = str_replace(
array('blah', 'blarh'),
array('bleh', 'blerh'),
$string
);
// Additional tip:
And if you are stuck with an associative array like in your example, you can split it up like that:
$searchReplaceArray = array(
'blah' => 'bleh',
'blarh' => 'blerh'
);
$result = str_replace(
array_keys($searchReplaceArray),
array_values($searchReplaceArray),
$string
);

$string = 'blah blarh bleh bleh blarh';
$trans = array("blah" => "blerh", "bleh" => "blerh");
$result = strtr($string,$trans);
You can check the manual for detailed explanation.

IN CASE some one is looking for replacing same strings with different values ( per occurence ).. Example, to replace all ## by numbers++ OR values from an array-
$split_at = '##';
$string = "AA ## BB ## CC ## DD";
$new_string = '';
// echo $string;
$replace_num = 1;
$replace_arr = ['first' , 'second' , 'third'];
$split_at_cnt = substr_count($string, $split_at);
for ($split=0; $split <= $split_at_cnt; $split++)
{
$new_string .= str_replace('##', ($replace_num++)." : ".$replace_arr[$split], substr( $string, 0, strpos($string, $split_at)+strlen($split_at)));
$string = substr($string, strpos($string, $split_at)+strlen($split_at));
}
echo $new_string;

str_replace() does that.
You can check the manual for more detailed explanation.

For what you've got there, just pass that array into str_replace as both the search and replace (using array_keys on the search parameter if you want to keep the array as-is).

Related

Shortest way to get matched patterns from a string with regex

I have pretty long string to parse, that looks like that (part of it)
$string = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;'
I need to get values for php variables from that string, which I do with preg_match:
preg_match("/FIRM_ID = (.*?);/", $string, $m);
$firm_id = trim($m[1]);
preg_match("/CLIENT_CODE = (.*?);/", $string, $m);
$client_code = trim($m[1]);
... and so on
I was wondering is there a way to do the same in one line? May be with preg_replace or other functions, so I would not have to declare $m variable first and then take out from that [1] element.
So the code supposed to look like
$firm_id = somefunction($string);
$client_code = somefunction($string);
Its not practical question, more theoretical. I know how to get result that I need, I want to know if there is a simpler and more elegant way.
Thanks.
If you remove spaces and replace ; with &, you can do this:
parse_str(str_replace([' ', ';'], ['', '&'], $string), $result);
Which yields an easy to use associative array:
Array
(
[FIRM_ID] => MC0356400000
[TAG] => EQTV
[CURR_CODE] => SUR
[CLIENT_CODE] => FR334
[LIMIT_KIND] => 1
[OPEN_BALANCE] => 4822.84
[OPEN_LIMIT] => 0.00
[LEVERAGE] => 0
)
So just echo $result['FIRM_ID'];
Match and capture key-value pairs and then combine into an array:
$re = '/(\w+)\s*=\s*([^;]*)/';
$str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1],$matches[2]));
See the PHP demo, result:
Array
(
[FIRM_ID] => MC0356400000
[TAG] => EQTV
[CURR_CODE] => SUR
[CLIENT_CODE] => FR334
[LIMIT_KIND] => 1
[OPEN_BALANCE] => 4822.84
[OPEN_LIMIT] => 0.00
[LEVERAGE] => 0
)
The regex is
/(\w+)\s*=\s*([^;]*)/
See is demo online.
Details:
(\w+) - Group 1: one or more word chars
\s*=\s* - a = enclosed with optional whitespace(s)
([^;]*) - Group 2: zero or more chars other than ;.
To "initialize" the variables each at a time, you may use a
$var_name = 'FIRM_ID';
$re = '/' . $var_name . '\s*=\s*\K[^;]*/';
$str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
preg_match($re, $str, $m);
print_r($m);
See the PHP demo.
The \K is the match reset operator that omits all text matched so far within the current match iteration.
You can also use list function after preg_match_all :
preg_match_all('/(\w[\w-]*)\h*=\h*([^;\h]+);/', $string, $matches);
list($firmId, $tag, $currCode, $clientCode, $limitKind, $openBalance, $openLimit, $leverage) = $matches[2];
echo $firmId;
//=> MC0356400000
echo $tag;
//=> EQTV
echo $clientCode;
//=> FR334
echo $openBalance;
//=> 4822.84

How to get an array from string, containing an array?

Is it possible to using a regular expression, or otherwise create a function that will convert a string containing the php array of any form, in the real array, which can operate?
For Example:
$str = "array(1, array(2), array('key' => 'value'))";
$arr = stringArrayToArray($str);
Maybe there is already such an implementation of task?
Or do not bother, but simply to use eval()?
$arr = eval("return $str;");
You can try explode() function.
Try it.
<?php
$str = "do you love me";
$arr = explode(' ', $str);
print_r($arr);
?>
You can just replace the array( with a [ and ) with ]
as shown below:
$str = "array(1, array(2), array('key' => 'value'))";
$str = str_replace(" ","",str_replace(",","[",$str));
$str = str_replace(")","",str_replace("array(","[",$str));
echo $str;
$arr = explode("[",$str);
var_dump($arr);
?>
this the best I could get.

php replace all occurances of key from array in string

maybe this is duplicate but i did't find good solution.
I have array
$list = Array
(
[hi] => 0
[man] => 1
);
$string="hi man, how are you? man is here. hi again."
It should produce $final_string = "0 1, how are you? 1 is here. 0 again."
How can I achieve it with smart way? Many thanks.
Off of the top of my head:
$find = array_keys($list);
$replace = array_values($list);
$new_string = str_ireplace($find, $replace, $string);
Can be done in one line using strtr().
Quoting the documentation:
If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
To get the modified string, you'd just do:
$newString = strtr($string, $list);
This would output:
0 1, how are you? 1 is here. 0 again.
Demo.
$text = strtr($text, $array_from_to)
See http://php.net/manual/en/function.strtr.php
preg_replace may be helpful.
<?php
$list = Array
(
'hi' => 0,
'man' => 1
);
$string="hi man, how are you? Man is here. Hi again.";
$patterns = array();
$replacements = array();
foreach ($list as $k => $v)
{
$patterns[] = '/' . $k . '/i'; // use i to ignore case
$replacements[] = $v;
}
echo preg_replace($patterns, $replacements, $string);

PHP - How can I find pull out only the integers in a string that separates the integers with two periods?

Say I have a string like this:
$string = '.30..5..12..184..6..18..201..1.'
How would I pull out each of the integers, stripping the periods, and store them into an array?
You could use this. You break the string up by all of the periods... but this only works if it is exactly like that; if there is other stuff in the middle for example 25.sdg.12 it wouldnt work.
<?php
$my_array = explode("..",$string);
$my_array[0] = trim($my_array[0]); //This removes the period in first part making '.30' into '30'
///XXX $my_array[-1] = trim($my_array[-1]); XXX If your string is always the same format as that you could just use 7 instead.
I checked and PHP doesn't support negative indexes but you can count the array list and just use that. Ex:
$my_index = count($my_array) - 1;
$my_array[$my_index] = trim($my_array[$my_index]); //That should replace '1.' with '1' no matter what format or length your string is.
?>
This will break up your string into an array and then loop through to grab numbers.
$string = '.30..5..12..184..6..18..201..1.';
$pieces = explode('.', $string);
foreach($pieces as $key=>$val) {
if( is_numeric($val) ) {
$numbers[] = $val;
}
}
Your numbers will be in the array $numbers
All I could think of.
<?php
$string = '.30..5..12..184..6..18..201..1.';
$r_string = str_replace("..", ",", $string);
$r_string = str_replace(".", ",", $r_string);
print_r(explode(",", $r_string));
?>
Or If you want to the array in a variable
<?php
$string = '.30..5..12..184..6..18..201..1.';
$r_string = str_replace("..", ",", $string);
$r_string = str_replace(".", ",", $r_string);
$arr_ex = explode(",", $r_string);
print_r($arr_ex);
?>
Someone else posted this but then removed their code, it works as intended:
<?php
$string = '.30..5..12..184..6..18..201..1.';
$numbers = array_filter (explode ('.', $string), 'is_numeric');
print_r ($numbers);
?>
Output:
Array (
[1] => 30
[3] => 5
[5] => 12
[7] => 184
[9] => 6
[11] => 18
[13] => 201
[15] => 1 )
try this ..
$string = '.30..5..12..184..6..18..201..1.';
$new_string =str_replace(".", "", str_replace("..", ",", $string));
print_r (explode(",",$new_string));
One line solution:
print_r(explode("..",substr($string,1,-1)));

PHP str_replace

I'm currently using str_replace to remove a usrID and the 'comma' immediately after it:
For example:
$usrID = 23;
$string = "22,23,24,25";
$receivers = str_replace($usrID.",", '', $string); //Would output: "22,24,25"
However, I've noticed that if:
$usrID = 25; //or the Last Number in the $string
It does not work, because there is not a trailing 'comma' after the '25'
Is there a better way I can be removing a specific number from the string?
Thanks.
YOu could explode the string into an array :
$list = explode(',', $string);
var_dump($list);
Which will give you :
array
0 => string '22' (length=2)
1 => string '23' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
Then, do whatever you want on that array ; like remove the entry you don't want anymore :
foreach ($list as $key => $value) {
if ($value == $usrID) {
unset($list[$key]);
}
}
var_dump($list);
Which gives you :
array
0 => string '22' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
And, finally, put the pieces back together :
$new_string = implode(',', $list);
var_dump($new_string);
And you get what you wanted :
string '22,24,25' (length=8)
Maybe not as "simple" as a regex ; but the day you'll need to do more with your elements (or the day your elements are more complicated than just plain numbers), that'll still work :-)
EDIT : and if you want to remove "empty" values, like when there are two comma, you just have to modifiy the condition, a bit like this :
foreach ($list as $key => $value) {
if ($value == $usrID || trim($value)==='') {
unset($list[$key]);
}
}
ie, exclude the $values that are empty. The "trim" is used so $string = "22,23, ,24,25"; can also be dealt with, btw.
Another issue is if you have a user 5 and try to remove them, you'd turn 15 into 1, 25 into 2, etc. So you'd have to check for a comma on both sides.
If you want to have a delimited string like that, I'd put a comma on both ends of both the search and the list, though it'd be inefficient if it gets very long.
An example would be:
$receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1);
An option similar to Pascal's, although I think a bit simipler:
$usrID = 23;
$string = "22,23,24,25";
$list = explode(',', $string);
$foundKey = array_search($usrID, $list);
if ($foundKey !== false) {
// the user id has been found, so remove it and implode the string
unset($list[$foundKey]);
$receivers = implode(',', $list);
} else {
// the user id was not found, so the original string is complete
$receivers = $string;
}
Basically, convert the string into an array, find the user ID, if it exists, unset it and then implode the array again.
I would go the simple way: add commas around your list, replace ",23," with a single comma then remove extra commas. Fast and simple.
$usrID = 23;
$string = "22,23,24,25";
$receivers = trim(str_replace(",$usrID,", ',', ",$string,"), ',');
With that said, manipulating values in a comma separated list is usually sign of a bad design. Those values should be in an array instead.
Try using preg:
<?php
$string = "22,23,24,25";
$usrID = '23';
$pattern = '/\b' . $usrID . '\b,?/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
Update: changed $pattern = '/$usrID,?/i'; to $pattern = '/' . $usrID . ',?/i';
Update2: changed $pattern = '/' . $usrID . ',?/i to $pattern = '/\b' . $usrID . '\b,?/i' to address onnodb's comment...
Simple way (providing all 2 digit numbers):
$string = str_replace($userId, ',', $string);
$string = str_replace(',,','', $string);

Categories