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

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]

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);

PHP - Regular Expressions with Double Quoted Strings

I'm trying to use regular expressions to extract a certain value from a string:
"exec_hash": "/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=", "events_collector": "thiiM0ahsieSiech1phithe6chahngoo8sah6aid\n"
The data I want is the hash between the quotation marks. The problem is that there are multiple quotes within the string and preg_match_all function isn't returning the correct data. I've been playing around with regex for a while but can't figure it out. Ultimately, I'd like that data to be returned into a value. Ex: $string1 = '/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=';
Correction: I'm using curl to grab the page content. The data isn't stored in a variable.
$matches = array();
$thing = preg_match_all('/hash": "(.*?)", "events/',$page,$matches); print_r($matches);
It spits out a long array of much more than just the hash
Can you use substr?
haven't tested this, but in theory...
$pos_of_comma = strpos($str, ",");
if($pos_of_comma !== false) {
$execHash = substr($str, 14, $pos_of_comma - 14);
}
It looks like it's json_decodable:
//Get the result from curl request:
$curlResult = '"exec_hash": "/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=", "events_collector": "thiiM0ahsieSiech1phithe6chahngoo8sah6aid\n"';
//Parse the result:
$parsedResult = json_decode($curlResult, true);
//Get the hash:
$hash = $parsedResult["exec_hash"];
Thank you for the suggestions.
I figured it out. I missed the escape delimiters in the expression.
preg_match_all("/exec_hash\": \"(.*?)\", /",$page,$matches);

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

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];

PHP get values from a comma separated string at commas without exploding and looping [duplicate]

This question already has answers here:
PHP explode in array
(3 answers)
Closed 6 years ago.
Is there a way to split a comma separated string at the commas, without first exploding it and looping through the array? I've got a string that is output from a database, which comes out the way I've shown below. I then split them into links.
But, given the string the way it is, can I get it into links without doing it the way I do below?
<?php
$tags = "fiction,non-fiction,horror,romance";
$tags = explode(',', $tags);
foreach( $tags as $tag ){
echo ''.$tag.'<br />';
}
?>
The final out of the above is:
fiction<br />
non-fiction<br />
horror<br />
romance<br />
You can use a single regex:
preg_replace('~\s?([^\s,]+)\s?(?:,|$)~', '$1<br />' . PHP_EOL, $tags);
\s? matches a single whitespace or nothing
([^\s,]+) matches everything until it reaches a whitespace or a comma and captures it
\s? again, matches a single whitespace or nothing
(?:,|$) matches either a comma or end of string
You could use array_walk instead of foreach but it amounts to pretty much the same.
array_walk(explode(',',$tags),function($tag){
echo ''.$tag.'<br />';
});
If you want to use tested, robust code that won't bug out when you have some values surrounded with quotes to escape an actual comma within the quoted string (where the naive approaches would still split), you could try using the str_getcsv function.
<?php
$tags = "fiction,non-fiction,horror,romance";
/*You can achieve that by using regular expresions*/
$pattern = '~(?|select ([a-z][^\W_]*+) | *+([a-z][^\W,_]*+) *+,?)~i';
//str_replace() function used for breaking the newline.
echo ''.str_replace(',', "<br/>", $tags).'';
?>

String with Double quoted and Single quoted

i have a string with double quote like this
$count = 5;
$str = "result: $count";
echo $str; //result: 5
variable parsing work well, and my problem is $count var must be define later than $str
$str = "result: $count";
$count = 5;
echo $str; //result:
So i will use single quote and ask a question here to finding a way to parse var whenever i want
$str = 'result: $count';
$count = 5;
//TODO: parse var process
echo $str; //result: 5
I'm will not using regex replace.
For this type of thing, I'd probably use string formatting. In PHP, that'd be printf.
?php
$str="result: %d"
....dostuff.....define $count.....
printf($str,$count)
?
edit:
although, the best way to do this probably depends partly on why you have to define $string before $count.
If it's a string that's repeated a lot, and you wanted to put it in a global variable or something, printf would be my choice, or putting it in a function as other answers have suggested.
If the string is only used once or twice, are you sure you can't refactor the code to make $count be defined before $string?
finally, a bit of bland theory:
when you write '$string = "result: $count"',
PHP immediately takes the value of $count and puts it into the string. after that, it isn't worried about $count anymore, for purposes of $string, and even if $count changes, $string won't, because it contains a literal copy of the value.
There isn't, as far as I'm aware, a way of binding a position in a string to a yet-to-be-defined variable. The 'printf' method leaves placeholders in the string, which the function printf replaces with values when you decide what should go in the placeholders.
So, if you wanted to only write
$string = "result: $count"
$count=5
$echo string
(and not have to call another function)
and get
"result: 5",
there's no way to do that. The closest method would be using placeholders and printf, but that requires an explicit call to a function, not an implicit substitution.
Why don't you use a function?
function result_str($count) { return "result: $count"; }
preg_replace is the simplest method. Something like this:
$str = preg_replace("/\\$([a-z0-9_]+)/ie", "$\\1", $str);
But if you really don't want to use a regex, then you'll have to parse the string manually, extract the variable name, and replace it.

Categories