Manipulating Strings in PHP with Functions - php

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.

Related

How to Explode the string in Codeigniter

I want to explore the following string which I am fetching from the database in CodeIgniter using a foreach loop. Actually, I am using a double delimiter to differentiate tags like SQL and MySQL because LIKE "%sql%" will return MySQL results as well. Should be LIKE "%|sql|%"
|login||background||signup||material-design|
I tried the following code but no success.
$snippettag_id = explode('|', $snippet_tags);
foreach($snippettag_id as $tag_id) {
$tag_name = $tag_id;
$this->db->or_like('snippets_name', $tag_name);
}
Your issue is with same delimiter and symbol in text, Here you need to replace your delimiter in db and in explode(), Try to save , instead of | as delimiter
$str = "|sql|,|Mysql|,|php|,|C#|,|C++|";//DB string
echo'<pre>';echo $str;
$strArray = explode(',', $str);
echo'<pre>';print_r($strArray);die;
Output:
|sql|,|Mysql|,|php|,|C#|,|C++|
Array
(
[0] => |sql|
[1] => |Mysql|
[2] => |php|
[3] => |C#|
[4] => |C++|
)
Apart from solution
you should probably normalize your database it will more reliable and easy to do searching in future
If you need the output as you mentioned above without using , characters so you can still do that easy
First run your query normal without any modification so results will be
$result = "login background signup material";
After that use explode with,
$snid = explode("," , $result);
Now you need | in your result you can do the following
$finalresult = str_ireplace(",", "|", "$snid");
Now output have | instead of ,

How to Convert $matches Array Output from preg_match_all in 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.

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)

How to extract parts using regular expression in PHP?

For example you have the following string:
$text = "word1:text1#atpart/foo/do/myfood$textfinal";
The function will work like:
$parts = array();
extract( $regular_exp, $text, $parts );
In the parts array we will get this:
$parts[0] = "word1";
$parts[1] = "text1";
$parts[2] = "atpart";
$parts[3] = "/foo/do/myfood";
$parts[4] = "textfinal";
Thanks!
This may not be what you are after, but the format you show looks almost like a URL with a username:password#domain authentication in front. If you can get the last $ to be served as a ?, it might be an idea to use parse_url() to parse it.
$string = "word1:text1#atpart/foo/do/myfood?textfinal"; // notice the ?
$string = "none://".$string; // We need to add a protocol for this to work
print_r (parse_url($string));
Result:
Array (
[scheme] => none
[host] => atpart
[user] => word1
[pass] => text1
[path] => /foo/do/myfood
[query] => textfinal )
the advantage of this would be that it's pretty flexible if one or more parts can be missing in the incoming data. If that's not an issue, a regex may be more convenient.
try
$parts = preg_split('/[:#\$]+/', $text);
Without more details, this matches the proposed example:
preg_match('#(.*?):(.*?)#(.*?)(/.*?)\$(.*)#', $text, $parts);
note that you will get the parts starting at index 1 instead of 0.
$delims=':#$';
$word = strtok('word1:text1#atpart/foo/do/myfood$textfinal',$delims);
while ( $word!==false ) {
foreach( explode('/',$word,2) as $tmp){
$words[]=$tmp;
}
$word = strtok($delims);
}
var_dump($words);
On one hand this is probably overkill. On the other hand, this may be more flexible depending on how different the string can be.
Demo: http://codepad.org/vy5b9yX7
Docs: http://php.net/strtok

preg_replace all characters up to a certain one

I have a string
&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&
and i have to delete, say, this part &185601651932|mobile|3|120|1& (starting with amp and ending with amp) knowing only the first number up to vertical line (185601651932)
so that in result i would have
&168491968426|mobile|3|100|1&114192088691|mobile|3|555|5&
How could i do that with PHP preg_replace function. The number of line (|) separated values would be always the same, but still, id like to have a flexible pattern, not depending on the number of lines in between the & sign.
Thanks.
P.S. Also, I would be greatful for a link to a good simply written resource relating regular expressions in php. There are plenty of them in google :) but maybe you happen to have a really great link
preg_replace("/&185601651932\\|[^&]+&/", ...)
Generalized,
$i = 185601651932;
preg_replace("/&$i\\|[^&]+&/", ...);
if you want real flexibility, use preg_replace_callback. http://php.net/manual/en/function.preg-replace-callback.php
Important: don't forget to escape your number using preg_quote():
$string = '&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$number = 185601651932;
if (preg_match('/&' . preg_quote($number, '/') . '.*?&/', $string, $matches)) {
// $matches[0] contains the captured string
}
It seems to me you ought to be using another data structure than a string to manipulate this data.
I'd want this data in a structure like
Array(
[id] => Array(
[field_1] => value_1
[field_2] => value_2
)
)
Your massive string can be massaged into such a structure by doing something like this:
$data_str = '168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$remove_num = '185601651932';
/* Enter a descriptive name for each of the numbers here
- these will be field names in the data structure */
$field_names = array(
'number',
'phone_type',
'some_num1',
'some_num2',
'some_num3'
);
/* split the string into its parts, and place them into the $data array */
$data = array();
$tmp = explode('&', trim($data_str, '&'));
foreach($tmp as $record) {
$fields = explode('|', trim($record, '|'));
$data[$fields[0]] = array_combine($field_names, $fields);
}
echo "<h2>Data structure:</h2><pre>"; print_r($data); echo "</pre>\n";
/* Now to remove our number */
unset($data[$remove_num]);
echo "<h2>Data after removal:</h2><pre>"; print_r($data); echo "</pre>\n";

Categories