php parsing a basic string contained in a variable [duplicate] - php

This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 7 years ago.
I'm new to php and have a basic question regarding parsing strings.
I have a variable "SKU" whose value is "9897_BLK"
I need to split this into two separate values:
"STYLE" with a value of "9897" AND "COLOR" with a value of "BLK"
I suppose there's a way to use the underscore to delimit the string.
Thanks for your help.

Try explode. This basically separates your string using a delimiter as your first parameter, and the string as the second parameter and returns an array of strings generated. Afterwards you can check if the string was properly parsed or you can just directly assign values just like the one below:
$sku = "9897_BLK";
$sku_parsed = explode("_", $sku);
$style = $sku_parsed[0];
$color = $sku_parsed[1];
If you want more details, the PHP manual is very accessible and has in-depth examples and use-cases for various scenario.
http://php.net/manual/en/function.explode.php

Try this:
$sku = "9897_BLK";
list($style, $color) = explode("_", trim($sku));

In PHP we use an function to split any string with delimiter.
You may try the explode function. The explode function return an array as output and the array values are the delimited values respectively.
Here is code snippet:
$SKU = "9897_BLK";
$DELIMITED_ARRAY = explode("_", $SKU);
$STYLE = $DELIMITED_ARRAY[0];
$COLOR = $DELIMITED_ARRAY[1];

Related

PHP implode and explode functions [duplicate]

This question already has answers here:
implode() string, but also append the glue at the end
(6 answers)
Closed 1 year ago.
I have this sentence:
piece:5,dozen:10
and I need to print it via php like this:
piece:5$,dozen:10$
without editing the line in the editor, I need php to do it automatically. Now I thought to split it like this:
$uom = "piece:5,dozen:10";
$lst1 = explode(',', $uom);
var_dump($lst1);
and it returned like this:
array (size=2)
0 => string 'piece:5' (length=7)
1 => string 'dozen:10' (length=8)
which is ok for now, so I need after each string piece:5$ dozen:10$ and then I did this:
$lst2 = implode('$ ', $lst1);
echo $lst2;
It printed:
piece:5$ dozen:10
I need the $ to be printed also after 10, so it will be like this:
piece:5$ dozen:10$
What is the right way to do this? What did I do wrong? What if the values are dynamically coming from the database?
You can use a combination of explode, array_map and implode like so:
<?php
$uom = 'piece:5,dozen:10';
$add_dollars = array_map(function($e) {
return $e . '$';
}, explode(',', $uom));
echo implode(" ", $add_dollars);
I see few explode-implode answers. I don't want to duplicate answer, so let me do it another way – with regex.
$data = "piece:5,dozen:10";
echo preg_replace("/(\d+)/i", "$1\$", $data);
It may be a good idea to make it a bit more complex, i.e. take not only \d+, but also previous string and colon. Rather without(!) comma. In my opinion this may be better (because it's usually worth to be strict in regex):
$data = "piece:5,dozen:10";
echo preg_replace("/([a-zA-Z]:\d+)/i", "$1\$", $data);
I encourage you to read php manual: preg_replace.
Answering also the question about jQuery – you don't need to use jQuery, you can do that in pure javascript. And it will be really similar! For example:
let data = "piece:5,dozen:10";
let modified = data.replace(/([a-zAZ]:\d+)/g,"$1\$");
console.log(modified);

i want to get specific data from a string [duplicate]

This question already has answers here:
How to use php serialize() and unserialize()
(10 answers)
Closed 5 years ago.
I want to split the string and get the specific data from this string. I am using MySQL and PHP.
I am having problems in retrieving data from database.
Here is the string:
a:6:{s:12:"cfdb7_status";s:6:"unread";s:9:"your-name";s:12:"Talha Far";s:10:"your-email";s:19:"talha4#gmail.com";s:6:"number";s:11:"03379228";s:9:"your-city";s:9:"Islamabad";s:10:"Studylevel";s:8:"Graduate";}
I want to get these values from string:
Talha Far , talha4#gmail.com , 03379228, Islamabad , Graduate
You could use unserialize() to transform the string into an object :
$str = 'a:6:{s:12:"cfdb7_status";s:6:"unread";s:9:"your-name";s:9:"Talha Far";s:10:"your-email";s:16:"talha4#gmail.com";s:6:"number";s:8:"03379228";s:9:"your-city";s:9:"Islamabad";s:10:"Studylevel";s:8:"Graduate";}';
$obj = unserialize($str) ;
var_dump($obj);
And your wanted values :
echo $obj['your-name'];
echo $obj['your-email'];
echo $obj['number'];
// ...
But, be carefull, some indices are wrong. Note the differences between your given string and the string in this anwser (ex: s:9:"Talha Far" instead of s:12:"Talha Far").
$str = 'a:6:{s:12:"cfdb7_status";s:6:"unread";s:9:"your-name";s:12:"Talha Far";s:10:"your-email";s:19:"talha4#gmail.com";s:6:"number";s:11:"03379228";s:9:"your-city";s:9:"Islamabad";s:10:"Studylevel";s:8:"Graduate";}';
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $str);
print_r(unserialize($data));
You will get your data array from it and you can extract your values.

How to set a PHP variable inside an `str_replace`? [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 7 years ago.
What is the correct form to make $id behave as a PHP variable inside the str_replace command? I've tried wrapping the $id inside with {, or ., but nothing helped. I'm not even sure how to define the problem I'm having here so I didn't really know how to Google this:
$id="Something";
$new = str_replace('?abc', '?id=$id&abc', $original);
There are two ways to concatenate strings in PHP. In your example, it would be either:
$new = str_replace('?abc', '?id=' . $id . '&abc', $original);
or
$new = str_replace('?abc', "?id=$id&abc", $original);
Note that the first option is slightly more efficient, and the spaces are optional.
i think it needs to be work like this.
$search = 's';
$replace = 'r';
$subject = 'subject';
$result = str_replace($search,$replace,$subject);
var_dump($result);
and the result will be 'rubject'.

Matching words in strings [duplicate]

This question already has answers here:
Php compare strings and return common values
(3 answers)
Closed 8 years ago.
I have two strings of keywords
$keystring1 = "tech,php,radio,love";
$keystring2 = "Mtn,huntung,php,tv,tech";
How do i do return keywords that common in both strings
You can do this:
$common = array_intersect(explode(",", $keystring1), explode(",", $keystring2));
If you want them back into strings, you can just implode it back.
Hmm, interesting question... You can use this.
$arr1 = explode(',',$keystring1);
$arr2 = explode(',',$keystring2);
$duplicates = array_intersect($arr1,$arr2);
foreach($duplicates as $word) {
echo $word;
}
You could explode() both strings on commas into arrays and loop through the first array checking to see if any of the words exist in the second array using the in_array() function. If so then add that word to a "common words" array.
Those are going to need to be arrays not variables.
$keystring1 = array('tech','php','radio','love');
$keystring2 = array('mtn','huntung','php','tv','tech');
First of all...

PHP: sscanf extract values from string within double quotes [duplicate]

This question already has an answer here:
How to unserialize an ArrayObject
(1 answer)
Closed 1 year ago.
I'm trying to parse the 2 values contained within double quotes from a session string. The other string variables are not constant and therefore can not use any additional characters as markers. I only need the quoted values. My following sscanf function is incomplete.
$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
sscanf($string,'%[^"]', $login_ip, $login_date);
echo $login_ip;
echo $login_date;
Thanks for your help.
That data is just PHP serialized text from serialize()
In which case you can get at the data you need with:
$sessionData = unserialize('a:1:{s:14:"174.29.144.241";s:8:"20110508";}');
list($ip, $date) = each($sessionData);
$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
preg_matches("/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/",$string,$matches);
echo $matches[1];
This should return your ip address. consult php.net
You can use regex to do that.
$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
$pattern = '/"(?P<ip>[^"]*)"[^"]*"(?P<date>[^"]*)"/';
preg_match( $pattern, $string, $matches );
echo $matches['ip'].' '.$matches['date'];
First quoted value will go to ip, second to date.
An interesting hack would be to use explode using " as the separator like this:
<?php
$res = explode('"','a:1:{s:14:"174.29.144.241";s:8:"20110508";}');
print_r($res);
?>
Any value in double quotes would be returned in an odd index i.e $res[1], $res[3]

Categories