$string = '763:74
74:274
177:474';
$number = array('763', '74', '177');
I need to get the corresponding values of $number
from $string
. Example: if number = 763
I need string value 74
. If number = 74
I need string value 274
and so on.
What right now what I'm doing is exploding $string
at :
character, looping and matching.
Looking for some better solution.
This should work for you:
First I split the string with preg_split()
and use a new line as delimiter (), where I also consume all spaces (
\s*
) on the right and left side, so you don't have them in the key:
preg_split("/\s*
\s*/", $string)
Then I go through each pair of numbers (x:y
) with array_map()
and explode()
it by a colon. So you end up with an array like this:
Array
(
[0] => Array
(
[0] => 763
[1] => 74
)
[1] => Array
(
[0] => 74
[1] => 274
)
[2] => Array
(
[0] => 177
[1] => 474
)
)
At the end I use array_column()
to say, that you want to use the 0st column as key and the 1st column as value.
Code:
<?php
$string = '763:74
74:274
177:474';
$result = array_column(
array_map(function($v){
return explode(":", $v);
}, preg_split("/\s*
\s*/", $string)
), 1, 0);
print_r($result);
?>
output:
Array
(
[763] => 74
[74] => 274
[177] => 474
)
You can do it using preg_match
- first you find the position of the key string, then you find the pair with that key to know the length of the pair.:
function find_in_string($n,$string){
preg_match("/(^|\s+)($n)(?=:)/",$string,$m1,PREG_OFFSET_CAPTURE);
preg_match("/(^|\s+)($n\:\d+)/",$string,$m2);
return substr($string,$m1[2][1]+ strlen($n)+1,strlen($m2[2])-strlen($n));
}
Example:
$string = '763:74
74:274
177:474';
foreach(array('763', '74', '177') as $n){
echo find_in_string($n,$string);
}
Output:
74
274
474
Demo:
http://sandbox.onlinephpfunctions.com/code/320e8ba1b47e62b75459aaf70f07994fe531b101
You can simply convert your string into an array simply using preg_replace_callback
like as
$string = '763:74
74:274
177:474';
$result = [];
preg_replace_callback('/(\d+):(\d+)/m',function($m)use(&$result){
$result[$m[1]] = $m[2];
},$string);
print_r($result);
output:
Array
(
[763] => 74
[74] => 274
[177] => 474
)