Easily extract data from string formatted a specific way - php

What is an easy way to take a string that is formatted this way:
c:7|bn:99
and be able to use that string easily? So if I wanted to get the number that is behind the c:, How could I get that easily. Same, thing with the number behind bn:?

You could use preg_match() function or you could use explode() function twice (first with | delimiter and second with : delimiter).
Example #1:
<?php
if( preg_match( '/^c:(\d+)\|bn:(\d+)$/', $sString, $aMatches ) )
{
print_r( $aMatches );
}
?>
Example #2:
<?php
$aPairs = explode('|', $sString ); // you have two elements in $aPairs
foreach( $aParis as $sPair )
{
print_r( explode(':', $sPair ) );
}
?>

$arr = array();
$str = "c:7|bn:99";
$tmp1 = explode('|', $str);
foreach($tmp1 as $val)
{
$tmp2 = explode(':', $val);
$arr[$tmp2[0]] = $tmp2[1];
}
//print ur array
print_r($arr);
//accessing specifc value
echo $arr['c']." ".$arr['bn'];

Try this:
$string = 'c:7|bn:99';
preg_match('/\Ac:([0-9]+)\|bn:([0-9]+)\z/', $string, $matches);
var_dump($matches);

If c & bn are not dynamic:
var_dump(sscanf("c:7|bn:99","c:%d|bn:%d"));
array(2) {
[0]=>
int(7)
[1]=>
int(99)
}

Related

php regex to extract single parameter value from string

I'm working with a string containing parameters, separated by some special characters in PHP with preg_match
An example could be like this one, which has four parameters.
1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?
Each parameter name is followed by ?#?, and its value is right next to it, ending with ?#? (note: values can be strings or numbers, and even special characters)
I've probably overcomplicated my regex, which works in SOME cases, but not if I search for the last parameter in the string..
This example returns 2222 as the correct value (in group 1) for 2ndParm
(?:.*)2ndParm\?#\?(.*?)\?#\?(?=.)(.*)
but it fails if 2ndParm is the last one in the string as in the following example:
1stparm?#?1111?#?2ndParm?#?2222?#?
I'd also appreciate help in just returning one group with my result.. i havent been able to do so, but since I always get the one I'm interested in group 1, I can get it easily anyway.
Without regex:
$str ='1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?';
$keyval = explode('?#?', trim($str, '?#'));
$result = [];
foreach($keyval as $item) {
[$key, $result[$key]] = explode('?#?', $item);
}
print_r($result);
demo
You don't need to use a regex for everything, and you should have a serious talk with whoever invented this horrid format about the fact that JSON, YAML, TOML, XML, etc exist.
function bizarre_unserialize($in) {
$tmp = explode('?#?', $in);
$tmp = array_filter($tmp); // remove empty
$tmp = array_map(
function($a) { return explode('?#?', $a); },
$tmp
);
// rearrange to key-value
return array_combine(array_column($tmp, 0), array_column($tmp, 1));
}
$input = '1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?';
var_dump(
bizarre_unserialize($input)
);
Output:
array(4) {
["1stparm"]=>
string(4) "1111"
["2ndParm"]=>
string(4) "2222"
["3rdParm"]=>
string(4) "3333"
["4thparm"]=>
string(3) "444"
}
You can use
(?P<key>.+?)
\Q?#?\E
(?P<value>.+?)
\Q?#?\E
in verbose mode, see a demo on regex101.com.
The \Q...\E construct disables the ? and # "super-powers" (no need to escape them here).
In PHP this could be
<?php
$string = "1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?";
$regex = "~(?P<key>.+?)\Q?#?\E(?P<value>.+?)\Q?#?\E~";
preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match["key"] . " = " . $match["value"] . "\n";
}
?>
Which yields
1stparm = 1111
2ndParm = 2222
3rdParm = 3333
4thparm = 444
Or shorter:
$result = array_map(
function($x) {return array($x["key"] => $x["value"]);}, $matches);
print_r($result);

How to extract string between two slashes php

i know that its easy to extract string between two slashes using explode() function in php, What if the string is like
localhost/used_cars/search/mk_honda/md_city/mk_toyota
i want to extract string after mk_ and till the slashes like:** honda,toyota **
any help would be highly appreciated.
I am doing like this
echo strpos(uri_string(),'mk') !== false ? $arr = explode("/", $string, 2);$first = $arr[0]; : '';
but not working because if user enter mk_honda in any position then explode() is failed to handle that.
Use regex:
http://ideone.com/DNHXsf
<?php
$input = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
preg_match_all('#/mk_([^/]*)#', $input, $matches);
print_r($matches[1]);
?>
Output:
Array
(
[0] => honda
[1] => toyota
)
Explode your string by /, then check every element of array with strpos:
$string = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$parts = explode('/', $string);
$r = [];
foreach ($parts as $p) {
// use `===` as you need `mk_` in position 0
if (strpos($p, 'mk_') === 0) {
// 3 is a length of `mk_`
$r[] = substr($p, 3);
}
}
echo'<pre>',print_r($r),'</pre>';
Just try this
$str='localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$str=explode('/',$str);
$final=[];
foreach ($str as $words){
(!empty(explode('_',$words)))?(isset(explode('_',$words)[1]))?$final[]=explode('_',$words)[1]:false:false;
}
$final=implode(',',$final);
echo $final;
It give output as
cars,honda,city,toyota

How to grab number after a word or symbol in PHP?

I want to grab a text with PHP just like for an example, There is a data "The apple=10" and I want to grab only the numbers from the data which looks exactly like that. I mean, the number's place would be after 'equals'.
and my problem is that the number from the source can be 2 or 3 characters or on the other word it is inconstant.
please help me to solve them :)
$string = "Apple=10 | Orange=3 | Banana=7";
$elements = explode("|", $string);
$values = array();
foreach($elements as $element)
{
$element = trim($element);
$val_array = explode("=", $element);
$values[$val_array[0]] = $val_array[1];
}
var_dump($values);
Output:
array(3) {
["Apple"]=> string(2) "10"
["Orange"]=> string(1) "3"
["Banana"]=> string(1) "7"
}
Hope thats how you need it :)
Well, php is a bit lazy about int conversion, so 12345blablabla can be converted to 12345:
$value = intval(substr($str, strpos($str, '=') + 1));
Of course, this is not the cleanest way but it is simple. If you want something cleaner, you could use a regexp:
preg_match ('#=([0-9]+)#', $str, $matches);
$value = intval($matches[1]) ;
Try the below code:
$givenString= "The apple=10";
$required_string = substr($givenString, strpos($givenString, "=") + 1);
echo "output = ".$required_string ; // output = 10
Using strpos() function, you can Find the position of the first occurrence of a substring in a string
and substr() function, Return part of a string.

Line and colon separated list to array PHP

I'm trying to work out a simple way to take a list, like this
foo: Alpha
bar: Bravo
fooBar: Charlie
And turn this into an associative array so that values would be
$array['foo'] //would contain Alpha
$array['bar'] //would contain Bravo
etc.
What is the cleanest way to achieve this ?
You can do it manually if your first list is already in an array:
$array = [];
$list = ['foo: Alpha', 'bar: Bravo'];
foreach ($list as $element) {
$parts = explode(': ', $element);
$array[$parts[0]] = $parts[1];
}
Otherwise, simply use parse_ini_string to parse a string that contains your data into an associative array (note that this function requires PHP 5.3 or greater).
If your data is in a string, and you don't have PHP 5.3, you can split on new lines to get an array: $list = explode("\n", $string);.
Something like this?:
$string = "foo: Alpha
bar: Bravo
fooBar: Charlie";
$array = array();
$lines = explode("\n", $string);
foreach ($lines as $line) {
list($key, $value) = explode(": ", $line);
$array[$key] = $value;
}
var_dump($array);
Result:
array(3) {
["foo"]=>
string(6) "Alpha
"
["bar"]=>
string(6) "Bravo
"
["fooBar"]=>
string(7) "Charlie"
}
Maybe this is overkill but if your file format is likely to expand, it's worth looking into YAML, your example happens to be valid YAML markup. So you could for example use the Symfony YAML component
use Symfony\Component\Yaml\Yaml;
$array = Yaml::parse('/path/to/file.yml');
It works with your current format and if you decide to add nested arrays or other non-trivial data, just use the YAML syntax, which is quite intuitive. Here is an introduction to the format:
http://symfony.com/doc/2.0/components/yaml/yaml_format.html
Try this :
$array = array();
$str = 'foo: Alpha';
$res = explode(":",$str);
$array[$res[0]] = $res[0];

How can I search for a string in an array, and then get what comes after same string until a point, in php?

EDIT: Parsed the array completely (it contained unparsed JSON!)
array(22) {
[0]=>
array(4) {
["responseData"]=>
array(1) {
["translatedText"]=>
string(163) "21558299 this is the text that i want to end up with, excluding the id number at the start of the string"
}
["responseDetails"]=>
string(0) ""
["responseStatus"]=>
int(200)
The string I want to search for is the 2155.. and IFF it's present, I want to get the string that's after it... How can I do this? Any help much appreciated! (Or a better solution...?)
What I need is a return boolean telling me if the ID is actually contained within array - if it is, I need the text. If it's not, I need to know as I want to put some other text (not relevant here).
Disclaimer: Gonna give this one to nickb, he's been beyond awesome.
EDIT: This part is irrelevant now:
This is what I got so far, but it's returning null. $trans_json is the array quoted above. $search[id] is another array, that holds the id string.
$return = array_filter( $trans_json, function($el) {
if( !( $start = strpos( $el, $search[id]) === false)) {
$str = substr( $el, $start);
return substr( $str, 0, strpos( $str, '}'));
}
return null;
});
Use array_walk():
Your example isn't working because $search is undefined. You need a closure (note the use ($search):
$search['id'] = '2s5d56b9712';
$return = array_walk( $trans_json, function( &$el) use( $search) {
if( !( ($start = strpos( $el, $search['id'])) === false)) {
$str = substr( $el, $start);
$el = substr( $str, strlen( $search['id']) + 1, strpos( $str, '}'));
}
});
var_dump( $trans_json);
See code below if it suits your need.
<?php
$subject = 'array(32) { [0]=> string(3266) "{"respString":{"feedbackText":"2s5d56b9712 the preceding id is the string i want to search for, and this is the rest of the text i want to get until here:"},"blablaarraycontinues...';
preg_match("/feedbackText\":\"2s5d(.*)\}/",$subject,$matches);
print_r($matches[1]); // output the matched string
?>

Categories