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]];}
}
Related
I have an array
Array
(
[0] => "http://example1.com"
[1] => "http://example2.com"
[2] => "http://example3.com"
...
)
And I want to replace the http with https of each elements using RegEx. I tried:
$Regex = "/http/";
$str_rpl = '${1}s';
...
foreach ($url_array as $key => $value) {
$value = preg_replace($Regex, $str_rpl, $value);
}
print_r($url_array);
But the result array is still the same. Any thought?
You actually print an array without changing it. Why do you need regex for this?
Edited with Casimir et Hippolyte's hint:
This is a solution using regex:
$url_array = array
(
0 => "http://example1.com",
1 => "http://example2.com",
2 => "http://example3.com",
);
$url_array = preg_replace("/^http:/i", "https:", $url_array);
print_r($url_array);
PHP Demo
Without regex:
$url_array = array
(
0 => "http://example1.com",
1 => "http://example2.com",
2 => "http://example3.com",
);
$url_array = str_replace("http://", "https://", $url_array);
print_r($url_array);
PHP Demo
First of all, you are not modifying the array values at all. In your example, you are operating on the copies of array values. To actually modify array elements:
use reference mark
foreach($foo as $key => &$value) {
$value = 'new value';
}
or use for instead of foreach loop
for($i = 0; $i < count($foo); $i++) {
$foo[$i] = 'new value';
}
Going back to your question, you can also solve your problem without using regex (whenever you can, it is always better to not use regex [less problems, simpler debugging, testing etc.])
$tmp = array_map(static function(string $value) {
return str_replace('http://', 'https://', $value);
}, $url_array);
print_r($tmp);
EDIT:
As Casimir pointed out, since str_replace can take array as third argument, you can just do:
$tmp = str_replace('http://', 'https://', $url_array);
This expression might also work:
^http\K(?=:)
which we can add more boundaries, and for instance validate the URLs, if necessary, such as:
^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)
DEMO
Test
$re = '/^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)/si';
$str = ' http://example1.com ';
$subst = 's';
echo preg_replace($re, $subst, trim($str));
Output
https://example1.com
The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.
RegEx Circuit
jex.im visualizes regular expressions:
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
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);
I want to split a string such as the following (by a divider like '~##' (and only that)):
to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date
into an array containing e.g.:
to => enquiry#test.com
subject => test
text => this is body/text
date => date
I'm using php5 and I've got the following regex, which almost works, but there are a couple of errors and there must be a way to do it in one go:
//Split the string in the url of $text at every ~##
$regexp = "/(?:|(?<=~##))(.*?=.*?)(?:~##|$|\/(?!.*~##))/";
preg_match_all($regexp, $text, $a);
//$a[1] is an array containing var1=content1 var2=content2 etc;
//Now create an array in the form [var1] = content, [var2] = content2
foreach($a[1] as $key => $value) {
//Get the two groups either side of the equals sign
$regexp = "/([^\/~##,= ]+)=([^~##,= ]+)/";
preg_match_all($regexp, $value, $r);
//Assign to array key = value
$val[$r[1][0]] = $r[2][0]; //e.g. $val['subject'] = 'hi'
}
print_r($val);
My queries are that:
It doesn't seem to capture more than 3 different sets of parameters
It is breaking on the # symbol and so not capturing email addresses e.g. returning:
to => enquiry
subject => test
text => this is body/text
I am doing multiple different regex searches where I suspect I would be able to do one.
Any help would be really appreciated.
Thanks
Why are you using regex when there is much simple method to do this by explode like this
$str = 'to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date';
$array = explode('~##',$str);
$finalArr = array();
foreach($array as $val)
{
$tmp = explode('=',$val);
$finalArr[$tmp['0']] = $tmp['1'];
}
echo '<pre>';
print_r($finalArr);
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)));