My code:
$url = "http://www.google.com/test";
$parseurl = parse_url($url);
$explode = explode('.', $parseurl['host']);
$arrayreverse = array_reverse($explode);
foreach(array_values($arrayreverse) as $keyvalue) {
$result[] = $keyvalue;
}
$implode = implode('.', $result);
...
I'm interested to have values in one variable from $implode result and the result if isset the path from $parseurl... how can I do that ?
EDIT:
I want the values of $implode + and(if isset $parseurl['path']); to be in 1 variable but I can't figure out how to unite them.
Is ths what you want?
$newurl = $implode . (isset($parseurl['path']) ? $parseurl['path'] : '');
It uses the conditional operator to return either the path or an empty string, and concatenate that onto $implode.
Related
i have these variables:
$pathPattern = '/catalog/{name}/{id}';
$pathRealUrl = '/catalog/test-product/12343';
The $pathPattern is dynamic, from a json file.
The $pathRealUrl is the url.
Now I need to create this two variables:
$name = 'test-product';
$id = 12343;
Note that the $pathPattern can have many variables
and also that {name} and {id} can have different name ( like {xxx} or {pippo} ), other sample:
$pathPattern = '/home/test/{hello}';
$pathRealUrl = '/home/test/alex';
The best way for archive this?
Split both string by / delimiter and loop through generated array from $pathPattern. In loop, get string that is between { and } and create variable named to it. At the end, set value of relevant index of $pathRealUrlArr in created variable.
$pathPatternArr = explode("/", $pathPattern);
$pathRealUrlArr = explode("/", $pathRealUrl);
foreach($pathPatternArr as $key=>$item){
if (preg_match("/^{(\w+)}$/", $item, $matches))
${$matches[1]} = $pathRealUrlArr[$key];
}
echo $name, $id;
See result in demo
You can shorten the code like bottom
foreach(explode("/", $pathPattern) as $key=>$item){
if (preg_match("/^{(\w+)}$/", $item, $matches))
${$matches[1]} = explode("/", $pathRealUrl)[$key];
}
echo $name, $id;
If the count of the number of values between the slashes will remain same or the position of the {name}/{id} will remain same then you can use explode to split the string by "/" and the get the desired values from the resultant array.
e.g.
$pathRealUrl = '/catalog/test-product/12343';
$array = explode("/",$pathRealUrl );
$id = $array[count($array)-1];
$name = $array[count($array)-2];
Ideone link : http://ideone.com/aNpxEJ
Hope it helps. :)
$pathPattern = '/catalog/{name}/{id}';
$pathRealUrl = '/catalog/test-product/12343';
$b = explode("/", $pathPattern);
$e = explode("/", $pathRealUrl);
$i = 0;
foreach ($b as $v) {
${substr($v,1,-1)} = $e[$i];
$i++;
}
echo $name;
echo $id;
And:
$i = 0;
foreach (explode("/", $pathPattern) as $v) {
${substr($v,1,-1)} = explode("/", $pathRealUrl)[$i];
$i++;
}
Show demo
I want to extract all used parameters of a link as a text string. Example:
$link2 = http://example.com/index.html?song=abcdefg;
When using the above link $param should give out all the parameters '?song=abcdefg'. Unfortunately I do not know the id index.html nor the parameters and their respective data values.
As much as I am informed there is the function $_GET, which creates an array, but I need a string.
You can use parse_url:
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = '?' . parse_url($link2, PHP_URL_QUERY);
echo $param;
// ?song=abcdefg
Many librairies exist to parse url, you can use this one for an exemple :
https://github.com/thephpleague/uri
use League\Uri\Schemes\Http as HttpUri;
$link2 = 'http://example.com/index.html?song=abcdefg';
$uri = HttpUri::createFromString($link2);
// then you can access the query
$query = $uri->query;
You also can try this one :
https://github.com/jwage/purl
A weird way to do this is
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = strstr($link2, "?");
echo $param // ?song=abcdefg
strstr($link2, "?") will get everything after the first position of ?; including the leading ?
you can loop over the get array and parse it into a string:
$str = "?"
foreach ($_GET as $key => $value) {
$temp = $key . "=". $value . "&";
$str .= $temp
}
rtrim($str, "&")//remove leading '&'
You can use http_build_query() method
if ( isset ($_GET))
{
$params = http_build_query($_GET);
}
// echo $params should return "song=abcdefg";
I looked up some reference like this question and this question but could not figure out what I need to do.
What I am trying to do is:
Say, I have two strings:
$str1 = "link/usa";
$str2 = "link/{country}";
Now I want to check if this the pattern matches. If they match, I want the value of country to be set usa.
$country = "usa";
I also want it to work in cases like:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
Maybe integers as well. Like match every braces and provide the variable with value. (And, yes better performance if possible)
I cannot get a work around since I am very new to regular expresssions. Thanks in advance.
It will give you results as expected
$str1 = "link/usa";
$str2 = "link/{country}";
if(preg_match('~link/([a-z]+)~i', $str1, $matches1) && preg_match('~link/{([a-z]+)}~i', $str2, $matches2)){
$$matches2[1] = $matches1[1];
echo $country;
}
Note: Above code will just parse alphabets, you can extend characters in range as per need.
UPDATE:
You can also do it using explode, see example below:
$val1 = explode('/', $str1);
$val2 = explode('/', $str2);
${rtrim(ltrim($val2[1],'{'), '}')} = $val1[1];
echo $country;
UPDATE 2
$str1 = "link/usa/texas/2/";
$str2 = "/link/{country}/{city}/{page}";
if(preg_match_all('~/([a-z0-9]+)~i', $str1, $matches1) && preg_match_all('~{([a-z]+)}~i', $str2, $matches2)){
foreach($matches2[1] as $key => $matches){
$$matches = $matches1[1][$key];
}
echo $country;
echo '<br>';
echo $city;
echo '<br>';
echo $page;
}
I don't see the point to use the key as variable name when you can built an associative array that will be probably more handy to use later and that avoids to write ugly dynamic variable names ${the_name_of_the_var_${of_my_var_${of_your_var}}}:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
function combine($pattern, $values) {
$keys = array_map(function ($i) { return trim($i, '{}'); },
explode('/', $pattern));
$values = explode('/', $values);
if (array_shift($keys) == array_shift($values) && count($keys) &&
count($keys) == count($values))
return array_combine($keys, $values);
else throw new Exception ("invalid format");
}
print_r(combine($str2, $str1));
Want to remove p2variable from url string, below are 3 cases if case 3 also remove ? sign.
case 1: http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p1=xyz&p3=ghj
case 2: http://www.domain.com/myscript.php?p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p3=ghj
case 3: http://www.domain.com/myscript.php?p2=10
result: http://www.domain.com/myscript.php
Want to achieve result with single preg_replace expression.
Don't use regular expressions when dealing with URL values. It's much easier (and safer) to handle them as a URL instead of plain text.
This could be one way to do it:
Split the url first and parse the query string
Take the parameter out
Rebuild the url
The below code is an example of such an algorithm:
// remove $qs_key from query string of $url
// return modified url value
function clean_url_qs($url, $qs_key)
{
// first split the url in two parts (at most)
$parts = explode('?', $url, 2);
// check whether query string is passed
if (isset($parts[1])) {
// parse the query string into $params
parse_str($parts[1], $params);
// unset if $params contains $qs_key
if (array_key_exists($qs_key, $params)) {
// remove key
unset($params[$qs_key]);
// rebuild the url
return $parts[0] .
(count($params) ? '?' . http_build_query($params) : '');
}
}
// no change required
return $url;
}
Test code:
echo clean_url('http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10', 'p2'), "\n";
Found this in one of my old projects (a bit of shitcode, but...), may help you:
$unwanted_param = 'p2';
$s = 'http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj';
$s = parse_url($s);
$params = explode('&', $s['query']);
$out_params = array();
foreach ($params as $key => &$param) {
list($name, $value) = explode('=', $param);
if ($unwanted_param == $name) {
unset($params[$key]);
} else {
$out_params[$name] = $value;
}
}
$query = '?' . http_build_query($out_params);
$result = $s['scheme'] . '://' . $s['host'] . $s['path'] . $query;
var_dump($result);
Using preg_replace, something like
$url = preg_replace('!([\?&]p2=[^&\?$]+)!i', '', $url);
However, personally I'd do the following
if (strpos($url, '?') !== false) {
list($domain, $qstring) = explode('?', $url, 2);
parse_str($qstring, $params);
if (isset($params['p2'])) {
unset($params['p2']);
}
$qstring = !empty($params) ? '?' . http_build_query($params) : '';
$url = $domain . $qstring;
}
What's the best way to accomplish the following.
I have strings in this format:
$s1 = "name1|type1"; //(pipe is the separator)
$s2 = "name2|type2";
$s3 = "name3"; //(in some of them type can be missing)
Let's assume nameN / typeN are strings and they can not contain a pipe.
Since I need to exctract the name / type separetly, I do:
$temp = explode('|', $s1);
$name = $temp[0];
$type = ( isset($temp[1]) ? $temp[1] : '' );
Is there an easier (smarter whatever faster) way to do this without having to do isset($temp[1]) or count($temp).
Thanks!
list($name, $type) = explode('|', s1.'|');
Note the order of arguments for explode()
list($name,$type) = explode( '|',$s1);
$type will be NULL for $s3, though it will give a Notice
I'm a fan of array_pop() and array_shift(), which don't error out if the array they use is empty.
In your case, that would be:
$temp = explode('|', $s1);
$name = array_shift($temp);
// array_shift() will return null if the array is empty,
// so if you really want an empty string, you can string
// cast this call, as I have done:
$type = (string) array_shift($temp);
There is not need to do isset since $temp[1] will exist and content an empty value. This works fine for me:
$str = 'name|type';
// if theres nothing in 'type', then $type will be empty
list($name, $type) = explode('|', $str, 2);
echo "$name, $type";
if(strstr($temp,"|"))
{
$temp = explode($s1, '|');
$name = $temp[0];
$type = $temp[1];
}
else
{
$name = $temp[0];
//no type
}
Maybe?