I have string like following format:
$string ='[(id,name,top,left,width,height,depth)filename|filename][(id,name,top,left,width,height,depth)filename|filename]';
I want to extract string for square and simple bracket and result set would be like
[0] =>(id,name,top,left,width,height,depth)
[1] => filename
[2] => filename
How can i do it? I have tried below code:
explode("[" , rtrim($string, "]"));
But not working properly.
You can use regex for this,
$re = "/\\[\\((.*?)\\)(.*?)\\]/s";
$str = "[(id,name,top,left,width,height,depth)filename|filename][(id,name,top,left,width,height,depth)filename|filename]'";
preg_match_all($re, $str, $matches);
output
matches[1][0] => id,name,top,left,width,height,depth
matches[1][1] => filename|filename
See
regex
Use this code
$string ='[(id,name,top,left,width,height,depth)filename|filename][(id,name,top,left,width,height,depth)filename|filename]';
$array = explode('][',$string);
$array = array_unique(array_filter($array));
$singleArr = array();
$singleArr[] = str_replace('[','',$array['0']);
$singleArr[] = str_replace(']','',$array['1']);
$singleArr = array_unique($singleArr);
//print_r($singleArr);
$blankArr = array();
foreach($singleArr as $val)
{
$first = explode('|',$val);
$blankArr['0'] = substr($first['0'],0,-8);
$blankArr['1'] = substr($first['0'],-8);
$blankArr['2'] = $first['1'];
}
print_r($blankArr);
Related
I have a string that contains multiple templated variables like this:
$str = "Hello ${first_name} ${last_name}";
How can I do to extract these variables in an array like this :
$array = ['first_name', 'last_name'];
Use single quotes instead of double quotes when describing the string.
$str = 'Hello ${first_name} ${last_name}';
preg_match_all('/{(.*?)}/s', $str, $output_array);
dd($output_array[1]);
Use explode function example given below:
$str = "Hello ${first_name} ${last_name}";
$str_to_array = explode("$",$str);
$array = array();
foreach($str_to_array as $data){
if (str_contains($data, '{')) {
$array[] = str_replace("}","",str_replace("{","",$data));
}
}
print_r($array);
You can use a simple regular expression and use preg_match_all to find all the ocurrences, like this:
<?php
$pattern = '|\${.*?}|';
$subject = 'Hello ${first_name} ${last_name}';
$matches = '';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
Result:
Array
(
[0] => Array
(
[0] => ${first_name}
[1] => ${last_name}
)
)
Currently, I've a script that is working perfectly! And I must use GET parameters at my situation, and unfortunately, my old smart tv still not able to recognize & symbol
e.g:
http://localhost/share.php?code=161494581&nativo=sim&url=http://cdn100.ntncc.stream/prop/httpdelivery/14004787mega.mp4&mediaType=fixit&mediaName=Mega&mediaClose=2000&idfy=1
In my smartv, the link stop at the first & symbol. So, I'll use a different symbol, like |
http://localhost/share.php|code=161494581|nativo=sim|url=http://cdn100.ntncc.stream/prop/httpdelivery/14004787mega.mp4|mediaType=fixit|mediaName=Mega|mediaClose=2000|idfy=1
And I'm trying to create a script to split all | symbol and after this, split = symbol to attribute the name to the respective value.
Here is my PHP script:
$string = "https://<private-urk>/player/share.php|code=161494581|nativo=sim|url=http://cdn100.ntncc.stream/prop/httpdelivery/14004787mega.mp4|mediaName=Megatubarão|mediaClose=2000|idfy= 1";
$split1 = explode('|', $string);
$arr = [];
foreach ($split1 as $value) {
$split2 = explode('=', $value);
$_GET[$split2[0]] = $split2[1];
echo $_GET[$split2[0]];
}
The script is not working, it's showing wrong the values, I've no idea about what I should to. Can you help me?
You could just replace the | with & again, strip out the URL and then use parse_str:
$string = "https://topflix.tv/player/share.php|code=161494581|nativo=sim|url=http://cdn1.ntcdn.stream/prop/httpdelivery/filmes/p1/14004787megatubarao-2018.mp4|mediaType=filme|mediaName=Megatubarão|mediaYear=2018|idfy= 1";
$string = substr($string, strpos($string, '|'));
parse_str(str_replace('|', '&', $string), $_GET);
print_r($_GET);
Output:
Array (
[code] => 161494581
[nativo] => sim
[url] => http://cdn1.ntcdn.stream/prop/httpdelivery/filmes/p1/14004787megatubarao-2018.mp4
[mediaType] => filme
[mediaName] => Megatubarão
[mediaYear] => 2018
[idfy] => 1
)
Demo on 3v4l.org
use this:
<?php
$string = "https://topflix.tv/player/share.php|code=161494581|nativo=sim|url=http://cdn1.ntcdn.stream/prop/httpdelivery/filmes/p1/14004787megatubarao-2018.mp4|mediaType=filme|mediaName=Megatubarão|mediaYear=2018|idfy=1";
$split1 = explode('|', $string);
foreach ($split1 as $value) {
$split2 = explode('=', $value);
if(isset($split2[1])){//check value
$_GET[$split2[0]] = $split2[1];
echo $_GET[$split2[0]];}
}
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
I have pretty long string to parse, that looks like that (part of it)
$string = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;'
I need to get values for php variables from that string, which I do with preg_match:
preg_match("/FIRM_ID = (.*?);/", $string, $m);
$firm_id = trim($m[1]);
preg_match("/CLIENT_CODE = (.*?);/", $string, $m);
$client_code = trim($m[1]);
... and so on
I was wondering is there a way to do the same in one line? May be with preg_replace or other functions, so I would not have to declare $m variable first and then take out from that [1] element.
So the code supposed to look like
$firm_id = somefunction($string);
$client_code = somefunction($string);
Its not practical question, more theoretical. I know how to get result that I need, I want to know if there is a simpler and more elegant way.
Thanks.
If you remove spaces and replace ; with &, you can do this:
parse_str(str_replace([' ', ';'], ['', '&'], $string), $result);
Which yields an easy to use associative array:
Array
(
[FIRM_ID] => MC0356400000
[TAG] => EQTV
[CURR_CODE] => SUR
[CLIENT_CODE] => FR334
[LIMIT_KIND] => 1
[OPEN_BALANCE] => 4822.84
[OPEN_LIMIT] => 0.00
[LEVERAGE] => 0
)
So just echo $result['FIRM_ID'];
Match and capture key-value pairs and then combine into an array:
$re = '/(\w+)\s*=\s*([^;]*)/';
$str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1],$matches[2]));
See the PHP demo, result:
Array
(
[FIRM_ID] => MC0356400000
[TAG] => EQTV
[CURR_CODE] => SUR
[CLIENT_CODE] => FR334
[LIMIT_KIND] => 1
[OPEN_BALANCE] => 4822.84
[OPEN_LIMIT] => 0.00
[LEVERAGE] => 0
)
The regex is
/(\w+)\s*=\s*([^;]*)/
See is demo online.
Details:
(\w+) - Group 1: one or more word chars
\s*=\s* - a = enclosed with optional whitespace(s)
([^;]*) - Group 2: zero or more chars other than ;.
To "initialize" the variables each at a time, you may use a
$var_name = 'FIRM_ID';
$re = '/' . $var_name . '\s*=\s*\K[^;]*/';
$str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
preg_match($re, $str, $m);
print_r($m);
See the PHP demo.
The \K is the match reset operator that omits all text matched so far within the current match iteration.
You can also use list function after preg_match_all :
preg_match_all('/(\w[\w-]*)\h*=\h*([^;\h]+);/', $string, $matches);
list($firmId, $tag, $currCode, $clientCode, $limitKind, $openBalance, $openLimit, $leverage) = $matches[2];
echo $firmId;
//=> MC0356400000
echo $tag;
//=> EQTV
echo $clientCode;
//=> FR334
echo $openBalance;
//=> 4822.84
Say I have a string like this:
$string = '.30..5..12..184..6..18..201..1.'
How would I pull out each of the integers, stripping the periods, and store them into an array?
You could use this. You break the string up by all of the periods... but this only works if it is exactly like that; if there is other stuff in the middle for example 25.sdg.12 it wouldnt work.
<?php
$my_array = explode("..",$string);
$my_array[0] = trim($my_array[0]); //This removes the period in first part making '.30' into '30'
///XXX $my_array[-1] = trim($my_array[-1]); XXX If your string is always the same format as that you could just use 7 instead.
I checked and PHP doesn't support negative indexes but you can count the array list and just use that. Ex:
$my_index = count($my_array) - 1;
$my_array[$my_index] = trim($my_array[$my_index]); //That should replace '1.' with '1' no matter what format or length your string is.
?>
This will break up your string into an array and then loop through to grab numbers.
$string = '.30..5..12..184..6..18..201..1.';
$pieces = explode('.', $string);
foreach($pieces as $key=>$val) {
if( is_numeric($val) ) {
$numbers[] = $val;
}
}
Your numbers will be in the array $numbers
All I could think of.
<?php
$string = '.30..5..12..184..6..18..201..1.';
$r_string = str_replace("..", ",", $string);
$r_string = str_replace(".", ",", $r_string);
print_r(explode(",", $r_string));
?>
Or If you want to the array in a variable
<?php
$string = '.30..5..12..184..6..18..201..1.';
$r_string = str_replace("..", ",", $string);
$r_string = str_replace(".", ",", $r_string);
$arr_ex = explode(",", $r_string);
print_r($arr_ex);
?>
Someone else posted this but then removed their code, it works as intended:
<?php
$string = '.30..5..12..184..6..18..201..1.';
$numbers = array_filter (explode ('.', $string), 'is_numeric');
print_r ($numbers);
?>
Output:
Array (
[1] => 30
[3] => 5
[5] => 12
[7] => 184
[9] => 6
[11] => 18
[13] => 201
[15] => 1 )
try this ..
$string = '.30..5..12..184..6..18..201..1.';
$new_string =str_replace(".", "", str_replace("..", ",", $string));
print_r (explode(",",$new_string));
One line solution:
print_r(explode("..",substr($string,1,-1)));