How to Convert $matches Array Output from preg_match_all in PHP - php

Using preg_match_all I retrieve (as an example) the follow string:
ABC033-101-143-147-175-142115-
Here is the code for that:
if (preg_match_all('#([A-Z]{2}C)((?:[0-9]{3}-){1,10})([0-9]{6})#', $wwalist, $matches))
I am able to get the output I want (033-101-143-147-175-) by using the following code:
$wwaInfo['locationabbrev'][$wwanum] = $matches[2][$keys[$wwanum]];
echo "locationabbrev";
From here, I need to convert the sets of 3 numbers. Every number has a corresponding abbreviation. For example, 033 = FY, 101 = CY, etc. I need locationabbrev to output a string like: "FY-CY-AY-GG-CA" as opposed to the numbers. Any idea how I would go about this?
Thanks for taking a look!

You can use strtr() with array of replacements. For example:
$locationabbrev = '033-101-143-147-175-'; // example data
// array of replacements
$replacements = [
'033' => 'FY',
'101' => 'CY',
// and so on
];
$translatedabbrev = strtr($locationabbrev, $replacements);
echo $translatedabbrev; // your final string

One method that uses explode and foreach.
Again, Tajgeers answer is very good. So unless you have some specific reason choose that.
This is just one more way to do it.
$repl = [
'033' => 'FY',
'101' => 'CY',
'143' => 'AY',
'147' => 'GG',
'175' => 'CA' ];
$locationabbrev = '033-101-143-147-175';
$arr = explode("-", $locationabbrev);
Foreach($arr as &$val){
$val= $repl[$val];
}
$result = implode("-", $arr);
Echo $result;
https://3v4l.org/iolal
Now that I think of it. If you change the regex slightly, you can get the output of the regex as my $arr. Meaning already exploded.
Still the other answer is better. Just a thought.

Related

How to search and replace comma separated numbers in a string based on an associative array in PHP? [duplicate]

This question already has answers here:
PHP replace multiple value using str_replace? [duplicate]
(3 answers)
Closed 1 year ago.
I have a string containing comma-separated numbers and I also have an associative array in PHP containing unique numbers. What I want to achieve is to create a new string that contains only the exact match replacements based on the array. Here is my code so far:
<?php
$replacements = array(
'12' => 'Volvo',
'13' => 'BMW',
'132' => 'Alfa Romea',
'156' => 'Honda',
'1536' => 'Tesla',
'2213' => 'Audi'
);
$str ="12,13,132,2213";
echo str_replace(array_keys($replacements), $replacements, $str);
?>
The only problem is that the output is this:
Volvo,BMW,BMW2,22BMW
instead of this:
Volvo,BMW,Alfa Romeo,Audi
How can I achieve exact match search and replace in this function? Is there a fastest PHP solution for this problem?
Thanks,
belf
Another one-liner. Combine explode the string keys, and flip it to serve as keys using array_flip, then finally, array_intersect_key to combine them by key. implode the remaining values combined:
$cars = implode(', ', array_intersect_key($replacements, array_flip(explode(',', $str))));
You may use this very simple, straight-forward, and easy to understand code:
$result = [];
foreach (explode(',', $str) as $id) {
$result[] = isset($replacements[$id]) ? $replacements[$id] : $id;
}
$str = implode(',', $result);

Manipulating Strings in PHP with Functions

I searched every single str_replace, preg_replace, substr on StackOverflow and can't wrap my head around this.
The strings in my data are as such: "010758-01-700" or "860862-L-714". These are just examples.
These strings are 's
Instance 1:
010758-01-700
/ImageServices/image.ashx?itemid=010758&config=01&format=l&imagenumber=1
If you look carefully at the URL and the string above it, I need to split this as "01075&config=01" and drop "-700" from the string to return a value I can insert into the URL
Instance 2:
860862-L-714
/ImageServices/image.ashx?itemid=870078&color=001&format=l&imagenumber=1
I need to split this as "860862&&color=714" and drop all instances of "-XXS-, -XS-, -S-, -M-, -L-, -XL- ,-XXL-" for the string to return a value I can insert into the URL
There are strings that look like this throughout the data, 860862-L-714, 860862-M-999, 860862-XS-744. These are variations of product with the same name but different
I have tried str_replace("-", "&config=", {ItemNo[1]}) but it returns 010758&config=01&config=700
I'd need to contain this all into a function that I can call into the URL
myFunction({ItemNo[1]})
Then I can setup the URL as so /ImageServices/image.ashx?itemid=
myFunction({ItemNo[1]})&format=l&imagenumber=1
and if my logic is correct, it should work. I'm using WP All Import to import XML data.
How do I create a function that will manipulate the string based on both instances above and output the results I'm trying to achieve?
Ok - based on the responses, I've solved the first instance to get the correct url to display - $content being the ItemNo
<?php
function ItemNoPart1 ( $content ) {
$content1 = explode("-", $content);
return $content1[0];
}
function ItemNoPart2 ( $content ) {
$content2 = explode("-", $content);
return $content2[1];
}
?>
/ImageServices/image.ashx?itemid=[ItemNoPart1({ItemNo[1]})]&config=[ItemNoPart2({ItemNo[1]})]&format=l&imagenumber=1
Now I just need to figure out how to do part 2 and combine it all into 1 function.
Don't use str_replace, use explode instead:
$str = '010758-01-700';
$chunks = explode( '-', $str );
By this way, resulting $chunks is an array like this:
[0] => 010758
[1] => 01
[2] => 700
So, now you can format desired URL in this way:
$url = "/ImageServices/image.ashx?itemid={$chunks[0]}&config={$chunks[1]}&format=l&imagenumber=1"
Your desired function is this:
function myFunction( $itemID )
{
$chunks = explode( '-', $itemID );
return "/ImageServices/image.ashx?itemid={$chunks[0]}&config={$chunks[1]}";
}
... but, really you want a function for this stuff?
Read more about explode()
Here's some psuedo code that may lead you in the right direction. The idea is to build out an array that contains all of the possible pieces of data from our string.
I've used a given constant of /ImageServices/image.ashx? to split upon, as we know the URL of our endpoint.
// explode our string into multiple parts
$parts = explode('/ImageServices/image.ashx?', $str);
// we know that the string we need to parse as at the index of 1
parse_str($parts[1], $parsed);
//$wanted will contain all of the data we can possibly need.
$wanted = array($parts[0], $parsed);
This will yield an array that looks like the following:
array (
0 => '860862-L-714 ',
1 =>
array (
'itemid' => '870078',
'color' => '001',
'format' => 'l',
'imagenumber' => '1',
),
)
Now you can perform your conditionals such as when you need to look for color and create a specific URL structure:
if(array_key_exists('color', $wanted[1]){
//create our custom sting structure here.
}
Hopefully this helps.

Something wrong with array

I'm using this code to get first number and replace it with 0-9, but I always get 0-0-9 result. Then I deleted in array 9 it started to work correct. why it works that way ?
$direction = strtoupper(substr($query_row["Band"],0,1));
$replace = [
'0' => '0-9','1' => '0-9','2' => '0-9','3' => '0-9','4' => '0-9',
'5' => '0-9','6' => '0-9','7' => '0-9','8' => '0-9', '9' => '0-9' ];
$dir= str_replace(array_keys($replace), $replace, $direction);
try this one
$search = array('0','1','2','3','4','5','6','7','8');
$replace = array('0-9','0-9','0-9','0-9','0-9','0-9','0-9','0-9','0-9');
$dir = str_replace($search, $replace, $direction);
and then work around for 9 which depends on your string
mine was 0123456789 so I tried
$dir = str_replace('99', '9,0-9', $dir);
its working on mine
It's explained in the documentation of str_replace():
Caution
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.
You pass arrays as first two arguments to str_replace(). This is the same as you would call str_replace() repeatedly for each element in the array.
If $direction is not '9' then it replaces it with '0-9'. Then, on the last cycle it replaces '9' from '0-9' with '0-9' (according to the values you passed it).
I would drop the code after the first line and read the first sentence again: "get first number and replace it with 0-9".
If your goal is to get the first character of $query_row["Band"] and replace it with 0-9 if it is a digit (and make it uppercase otherwise) I would write something more simple:
$direction = substr($query_row["Band"], 0, 1);
if (is_numeric($direction)) {
$dir = '0-9';
} else {
$dir = strtoupper($direction);
}

Error parsing regex pattern in php

I want to split a string such as the following (by a divider like '~##' (and only that)):
to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date
into an array containing e.g.:
to => enquiry#test.com
subject => test
text => this is body/text
date => date
I'm using php5 and I've got the following regex, which almost works, but there are a couple of errors and there must be a way to do it in one go:
//Split the string in the url of $text at every ~##
$regexp = "/(?:|(?<=~##))(.*?=.*?)(?:~##|$|\/(?!.*~##))/";
preg_match_all($regexp, $text, $a);
//$a[1] is an array containing var1=content1 var2=content2 etc;
//Now create an array in the form [var1] = content, [var2] = content2
foreach($a[1] as $key => $value) {
//Get the two groups either side of the equals sign
$regexp = "/([^\/~##,= ]+)=([^~##,= ]+)/";
preg_match_all($regexp, $value, $r);
//Assign to array key = value
$val[$r[1][0]] = $r[2][0]; //e.g. $val['subject'] = 'hi'
}
print_r($val);
My queries are that:
It doesn't seem to capture more than 3 different sets of parameters
It is breaking on the # symbol and so not capturing email addresses e.g. returning:
to => enquiry
subject => test
text => this is body/text
I am doing multiple different regex searches where I suspect I would be able to do one.
Any help would be really appreciated.
Thanks
Why are you using regex when there is much simple method to do this by explode like this
$str = 'to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date';
$array = explode('~##',$str);
$finalArr = array();
foreach($array as $val)
{
$tmp = explode('=',$val);
$finalArr[$tmp['0']] = $tmp['1'];
}
echo '<pre>';
print_r($finalArr);

str_replace and arrays that are not in order

I'm stuck with this.
I've got a huge template that goes like this (simplified for this question):
$str = '[a] [b] [c]';
Then I have an array containing those above values:
$arr = array('[a]','[b]','[c]','[d]');
And finally, containing the values for replace comes an array that does not match the above one.
$rep = array("[d]" => "dVal","[a]" => "aVal","[b]" => "bVal", "[c]" => "cVal");
Can I some how, by some technique or any other php function match the $rep array to replace the key with the same name in $str. I current use str_replace.
sr_replace($arr,$rep,$str);//
The key names and names in $str are the same.
str_replace(array_keys($rep), array_values($rep), $str)

Categories