Check an part of url exist in php - php

I have an URL:
http://abv.com/
How can I check if /en/ is in the URL, for example:
http://abv.com/en/

You can use strpos().
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// The !== operator can also be used. Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}

The simplest way to do that is using strpos():
if (strpos($url, '/en/') !== false) {
// found!
}
If you want to check just the path, though, using parse_url() can be helpful:
if (strpos(parse_url($url, PHP_URL_PATH), '/en/') !== false) {
// found in the path!
}

You can seperate url using php explode function, then check if url having "en" (country code ) or not.
$url = 'http://abv.com/en/';
$expurl = explode('/', $url);
print_r($expurl);
foreach ($expurl as $key => $value) {
if ($value == 'en') {
# do what you want
}
}
Array result
Array ( [0] => http: [1] => [2] => abv.com [3] => en [4] => )

You can take the URL and split it by slashes - use the .explode() function.
$url = 'http://abv.com/en/';
$urlParts = explode('/',$url);
array_shift($urlParts);
array_shift($urlParts);
Using array_shift() twice you remove the unwanted http and the blank item due to the double slash...
Array
(
[0] => abv.com
[1] => en
[2] =>
)
.parse_url() also has some usefull features for dealing with URL strings. You should check it out also.
$url = 'http://abv.com/en/';
$urlParts = parse_url($url);
$pathParts = explode('/',$urlParts['path']);

Related

How to check if URL contains certain words?

I want to show custom content if current URL contain certain words.
So far, I'm able to achieve this if the URL contains just the word, 'cart', using the code below. However, I want to be able to check for other words like 'blog', 'event' and 'news'. How do I go about this.
<?php $path = $_SERVER['REQUEST_URI'];
$find = 'cart';
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) :
?>
Custom content
<?php else: ?>
Use an array but use preg_grep instead. IMO it's the correct preg_ function for this use case.
preg_grep — Return array entries that match the pattern
//www.example.com?foo[]=somewords&foo[]=shopping+cart
//for testing
$_GET['foo'] = ['somewords', 'shopping cart'];
$foo = empty($_GET['foo']) ? [] : $_GET['foo'];
$words = ['cart','foo','bar'];
$words = array_map(function($item){
return preg_quote($item,'/');
},$words);
$array = preg_grep('/\b('.implode('|', $words).')\b/', $foo);
print_r($array);
Output
Array
(
[1] => shopping cart
)
Sandbox
Use an Array and loop through it .. IE
<?php $path = $_SERVER['REQUEST_URI'];
$arr = array();
$arr[0] = 'cart';
$arr[1] = 'foo';
$arr[2] = 'bar';
foreach($arr as $find){
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false){
echo "custom content";
break; // To exit the loop if custom content is found -- Prevents it showing twice or more
}
}
There are several solutions such as preg_match_all():
Code
<?php $path = $_SERVER['REQUEST_URI'];
$find = '/(curt|blog|event|news)/i';
$number_of_words_in_my_path = preg_match_all($find, $path);
if ($number_of_words_in_my_path > 0 && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) :
?>
Custom content
<?php else: ?>

parse string for subdomain in php

How can i find if a string has subdomain existing if there is no scheme / host present.
eg: $url="sub.main.com/images/sample.jpg";
I am trying to parse the url for images, and I am using parse_url for most cases.
But given the url strings can some in different flavors,
eg:
/images/sample.jpg
//main.com/images/sample.jpg
images/sample.jpg
etc, I am trying to address the different cases one by one. Right now, I am finding it hard to detect if a string has subdomain present or not.
so for a string such as $url="sub.main.com/images/sample.jpg";` i would like to extract the subdomain, and for a string such as images/sample.jpg, i would like to find out that there is no subdomain
Interesting problem. I've fiddled around with this for a while; this method inevitably isn't perfect, but it may start you down the right path.
My solution begins with the two source files in this repository: https://github.com/usrflo/registered-domain-libs/tree/master/PHP
First, you may need to modify regDomain.inc.php to change an instance of $signingDomainParts = split('\.', $signingDomain); to $signingDomainParts = preg_split('/\./', $signingDomain); if split is deprecated in your php version.
Once you've got those saved, try this testing code, I put all of the URLs mentioned in the thread here as test cases:
<?php
require_once("effectiveTLDs.inc.php");
require_once("regDomain.inc.php");
$tests = Array("/images/sample.jpg","//main.com/images/sample.jpg","images/sample.jpg", "sub.main.com/images/sample.jpg", "http://www.example.com/www.google.com/sample.jpg", "amazon.co.uk/images/sample.jpg", "amazon.com/images/sample.jpg", "http://sub2.sub.main.co.uk/images/sample.jpg", "sub2.sub.main.co.uk/images/sample.jpg");
foreach($tests as $test)
{
echo "Attempting $test.<BR/>";
$one = parse_url($test);
if(!array_key_exists("host", $one))
{
echo "Converting to: http://$test";
echo "<BR/>";
$one = parse_url("http://$test");
}
if(!$one){echo "<BR/>";continue;}
echo "parse_url parts: ";
print_r($one);
echo "<BR/>";
if($one && array_key_exists("host", $one))
{
$domain = getRegisteredDomain($one["host"], $tldTree);
if(sizeof($domain))
{
$two = explode(".", $domain);
echo "domain parts: ";
print_r($two);
echo "<BR/>";
if(sizeof($two))
{
$three = array_diff(explode(".", $one["host"]), $two);
if(sizeof($three))
{
echo "Hark! A subdomain!: ";
print_r($three);
echo "<BR/>";
}
}
}
}
echo "<BR/>";
}
?>
This code identifies the following of the test-cases as having subdomains:
Attempting sub.main.com/images/sample.jpg.
Hark! A subdomain!: Array ( [0] => sub )
Attempting http://www.example.com/www.google.com/sample.jpg.
Hark! A subdomain!: Array ( [0] => www )
Attempting http://sub2.sub.main.co.uk/images/sample.jpg.
Hark! A subdomain!: Array ( [0] => sub2 [1] => sub )
Attempting sub2.sub.main.co.uk/images/sample.jpg.
Hark! A subdomain!: Array ( [0] => sub2 [1] => sub )
Try this code
<?php
$url = 'sub.main.com/images/sample.jpg';
$arr = explode('/',$url);
$domain = $arr[0];
$string = $arr[1];
$arr2 = explode('.',$domain);
if(count($arr2)>2) {
$subdomain = $arr2[0];
echo $subdomain;
}
?>
<?php
$url = 'http://sub.main.com/images/sample.jpg';
$arr = explode('/',$url);
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))
{
$main_domain=$regs['domain'];
}
$host=$pieces['host'];
$path=$pieces['path'];
if($host != $main_domain)
{
$arr2 = explode('.',$host);
$subdomain = $arr2[0];
echo $subdomain;
}
$string=substr($path,1,strlen($path));
?>
Try the following:
<?php
$url="sub.main.com/images/sample.jpg";
preg_match('#^(?:http://)?([^.]+).?([^/]+)#i',$url, $hits);
print_r($hits);
?>
This should output something like:
Array ( [0] => sub.main.com [1] => sub [2] => main.com )

How to remove the querystring and get only the URL?

I'm using PHP to build the URL of the current page. Sometimes, URLs in the form of
www.example.com/myurl.html?unwantedthngs
are requested. I want to remove the ? and everything that follows it (querystring), such that the resulting URL becomes:
www.example.com/myurl.html
My current code is this:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" .
$_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
You can use strtok to get string before first occurence of ?
$url = strtok($_SERVER["REQUEST_URI"], '?');
strtok() represents the most concise technique to directly extract the substring before the ? in the querystring. explode() is less direct because it must produce a potentially two-element array by which the first element must be accessed.
Some other techniques may break when the querystring is missing or potentially mutate other/unintended substrings in the url -- these techniques should be avoided.
A demonstration:
$urls = [
'www.example.com/myurl.html?unwantedthngs#hastag',
'www.example.com/myurl.html'
];
foreach ($urls as $url) {
var_export(['strtok: ', strtok($url, '?')]);
echo "\n";
var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
echo "\n";
var_export(['explode/2: ', explode('?', $url, 2)[0]]); // limit allows func to stop searching after first encounter
echo "\n";
var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]); // not reliable; still not with strpos()
echo "\n---\n";
}
Output:
array (
0 => 'strtok: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'strstr/true: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'explode/2: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'substr/strrpos: ',
1 => 'www.example.com/myurl.html',
)
---
array (
0 => 'strtok: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'strstr/true: ',
1 => false, // bad news
)
array (
0 => 'explode/2: ',
1 => 'www.example.com/myurl.html',
)
array (
0 => 'substr/strrpos: ',
1 => '', // bad news
)
---
Use PHP Manual - parse_url() to get the parts you need.
Edit (example usage for #Navi Gamage)
You can use it like this:
<?php
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
return $constructed_url;
}
?>
Edit (second full example):
Updated function to make sure scheme will be attached and none notice msgs appear:
function reconstruct_url($url){
$url_parts = parse_url($url);
$constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');
return $constructed_url;
}
$test = array(
'http://www.example.com/myurl.html?unwan=abc',
`http://www.example.com/myurl.html`,
`http://www.example.com`,
`https://example.com/myurl.html?unwan=abc&ab=1`
);
foreach($test as $url){
print_r(parse_url($url));
}
Will return:
Array
(
[scheme] => http
[host] => www.example.com
[path] => /myurl.html
[query] => unwan=abc
)
Array
(
[scheme] => http
[host] => www.example.com
[path] => /myurl.html
)
Array
(
[scheme] => http
[host] => www.example.com
)
Array
(
[path] => example.com/myurl.html
[query] => unwan=abc&ab=1
)
This is the output from passing example URLs through parse_url() with no second parameter (for explanation only).
And this is the final output after constructing URL using:
foreach($test as $url){
echo reconstruct_url($url) . '<br/>';
}
Output:
http://www.example.com/myurl.html
http://www.example.com/myurl.html
http://www.example.com
https://example.com/myurl.html
best solution:
echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
No need to include your http://example.com in your <form action=""> if you're submitting a form to the same domain.
$val = substr( $url, 0, strrpos( $url, "?"));
Most Easiest Way
$url = 'https://www.youtube.com/embed/ROipDjNYK4k?rel=0&autoplay=1';
$url_arr = parse_url($url);
$query = $url_arr['query'];
print $url = str_replace(array($query,'?'), '', $url);
//output
https://www.youtube.com/embed/ROipDjNYK4k
You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:
$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];
Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing
You can use the parse_url build in function like that:
$baseUrl = $_SERVER['SERVER_NAME'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
You can try:
<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>
If you want to get request path (more info):
echo parse_url($_SERVER["REQUEST_URI"])['path']
If you want to remove the query and (and maybe fragment also):
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);
could also use following as per the php manual comment
$_SERVER['REDIRECT_URL']
Please note this is working only for certain PHP environment only and follow the bellow comment from that page for more information;
Purpose: The URL path name of the current PHP file, path-info is N/A
and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original
call URL).
Caveat: Not set on all PHP environments, and definitely only ones with
URL rewrites.
Works on web mode: Yes
Works on CLI mode: No
explode('?', $_SERVER['REQUEST_URI'])[0]
To remove the query string from the request URI, replace the query string with an empty string:
function request_uri_without_query() {
$result = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
if(!empty($query)) {
$result = str_replace('?' . $query, '', $result);
}
return $result;
}
Because I deal with both relative and absolute URLs, I updated veritas's solution like the code below.
You can try yourself here: https://ideone.com/PvpZ4J
function removeQueryStringFromUrl($url) {
if (substr($url,0,4) == "http") {
$urlPartsArray = parse_url($url);
$outputUrl = $urlPartsArray['scheme'] . '://' . $urlPartsArray['host'] . ( isset($urlPartsArray['path']) ? $urlPartsArray['path'] : '' );
} else {
$URLexploded = explode("?", $url, 2);
$outputUrl = $URLexploded[0];
}
return $outputUrl;
}
Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos:
$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];
Try this
$url_with_querystring = 'www.example.com/myurl.html?unwantedthngs';
$url_data = parse_url($url_with_querystring);
$url_without_querystring = str_replace('?'.$url_data['query'], '', $url_with_querystring);
Try this:
$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']
or
$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']

Convert PostgreSQL array to PHP array

I have trouble reading Postgresql arrays in PHP. I have tried explode(), but this breaks arrays containing commas in strings, and str_getcsv() but it's also no good as PostgreSQL doesn't quote the Japanese strings.
Not working:
explode(',', trim($pgArray['key'], '{}'));
str_getcsv( trim($pgArray['key'], '{}') );
Example:
// print_r() on PostgreSQL returned data: Array ( [strings] => {または, "some string without a comma", "a string, with a comma"} )
// Output: Array ( [0] => または [1] => "some string without a comma" [2] => "a string [3] => with a comma" )
explode(',', trim($pgArray['strings'], '{}'));
// Output: Array ( [0] => [1] => some string without a comma [2] => a string, with a comma )
print_r(str_getcsv( trim($pgArray['strings'], '{}') ));
If you have PostgreSQL 9.2 you can do something like this:
SELECT array_to_json(pg_array_result) AS new_name FROM tbl1;
The result will return the array as JSON
Then on the php side issue:
$array = json_decode($returned_field);
You can also convert back. Here are the JSON functions page
As neither of these solutions work with multidimentional arrays, so I offer here my recursive solution that works with arrays of any complexity:
function pg_array_parse($s, $start = 0, &$end = null)
{
if (empty($s) || $s[0] != '{') return null;
$return = array();
$string = false;
$quote='';
$len = strlen($s);
$v = '';
for ($i = $start + 1; $i < $len; $i++) {
$ch = $s[$i];
if (!$string && $ch == '}') {
if ($v !== '' || !empty($return)) {
$return[] = $v;
}
$end = $i;
break;
} elseif (!$string && $ch == '{') {
$v = pg_array_parse($s, $i, $i);
} elseif (!$string && $ch == ','){
$return[] = $v;
$v = '';
} elseif (!$string && ($ch == '"' || $ch == "'")) {
$string = true;
$quote = $ch;
} elseif ($string && $ch == $quote && $s[$i - 1] == "\\") {
$v = substr($v, 0, -1) . $ch;
} elseif ($string && $ch == $quote && $s[$i - 1] != "\\") {
$string = false;
} else {
$v .= $ch;
}
}
return $return;
}
I haven't tested it too much, but looks like it works.
Here you have my tests with results:
var_export(pg_array_parse('{1,2,3,4,5}'));echo "\n";
/*
array (
0 => '1',
1 => '2',
2 => '3',
3 => '4',
4 => '5',
)
*/
var_export(pg_array_parse('{{1,2},{3,4},{5}}'));echo "\n";
/*
array (
0 =>
array (
0 => '1',
1 => '2',
),
1 =>
array (
0 => '3',
1 => '4',
),
2 =>
array (
0 => '5',
),
)
*/
var_export(pg_array_parse('{dfasdf,"qw,,e{q\"we",\'qrer\'}'));echo "\n";
/*
array (
0 => 'dfasdf',
1 => 'qw,,e{q"we',
2 => 'qrer',
)
*/
var_export(pg_array_parse('{,}'));echo "\n";
/*
array (
0 => '',
1 => '',
)
*/
var_export(pg_array_parse('{}'));echo "\n";
/*
array (
)
*/
var_export(pg_array_parse(null));echo "\n";
// NULL
var_export(pg_array_parse(''));echo "\n";
// NULL
P.S.: I know this is a very old post, but I couldn't find any solution for postgresql pre 9.2
Reliable function to parse PostgreSQL (one-dimensional) array literal into PHP array, using regular expressions:
function pg_array_parse($literal)
{
if ($literal == '') return;
preg_match_all('/(?<=^\{|,)(([^,"{]*)|\s*"((?:[^"\\\\]|\\\\(?:.|[0-9]+|x[0-9a-f]+))*)"\s*)(,|(?<!^\{)(?=\}$))/i', $literal, $matches, PREG_SET_ORDER);
$values = [];
foreach ($matches as $match) {
$values[] = $match[3] != '' ? stripcslashes($match[3]) : (strtolower($match[2]) == 'null' ? null : $match[2]);
}
return $values;
}
print_r(pg_array_parse('{blah,blah blah,123,,"blah \\"\\\\ ,{\100\x40\t\daő\ő",NULL}'));
// Array
// (
// [0] => blah
// [1] => blah blah
// [2] => 123
// [3] =>
// [4] => blah "\ ,{## daőő
// [5] =>
// )
var_dump(pg_array_parse('{,}'));
// array(2) {
// [0] =>
// string(0) ""
// [1] =>
// string(0) ""
// }
print_r(pg_array_parse('{}'));
var_dump(pg_array_parse(null));
var_dump(pg_array_parse(''));
// Array
// (
// )
// NULL
// NULL
print_r(pg_array_parse('{または, "some string without a comma", "a string, with a comma"}'));
// Array
// (
// [0] => または
// [1] => some string without a comma
// [2] => a string, with a comma
// )
If you can foresee what kind text data you can expect in this field, you can use array_to_string function. It's available in 9.1
E.g. I exactly know that my array field labes will never have symbol '\n'. So I convert array labes into string using function array_to_string
SELECT
...
array_to_string( labels, chr(10) ) as labes
FROM
...
Now I can split this string using PHP function explode:
$phpLabels = explode( $pgLabes, "\n" );
You can use any sequence of characters to separate elements of array.
SQL:
SELECT
array_to_string( labels, '<--###DELIMITER###-->' ) as labes
PHP:
$phpLabels = explode( '<--###DELIMITER###-->', $pgLabes );
As #Kelt mentioned:
Postgresql arrays look like this: {1,2,3,4}
You can just simply replace first { and last } with [ and ]
respectively and then json_decode that.
But his solution works only for one-dimensional arrays.
Here the solution either for one-dimensional and multidimensional arrays:
$postgresArray = '{{1,2},{3,4}}';
$phpArray = json_decode(str_replace(['{', '}'], ['[', ']'], $postgresArray)); // [[1,2],[3,4]]
To cast back:
$phpArray=[[1,2],[3,4]];
$postgresArray=str_replace(['[', ']'], ['{', '}'], json_encode($phpArray));
Based on the answers in the thread i created two simple php functions that can be of use:
private function pgArray_decode(string $pgArray){
return explode(',', trim($pgArray, '{}'));
}
private function pgArray_encode(array $array){
$jsonArray = json_encode($array, true);
$jsonArray = str_replace('[','{',$jsonArray);
$jsonArray = str_replace(']','}',$jsonArray);
return $jsonArray;
}
I tried the array_to_json answer, but unfortunalety this results in an unknown function error.
Using the dbal query builder on a postgres 9.2 database with something like ->addSelect('array_agg(a.name) as account_name'), I got as result a string like { "name 1", "name 2", "name 3" }
There are only quotes around the array parts if they contain special characters like whitespace or punctuation.
So if there are quotes, I make the string a valid json string and then use the build-in parse json function. Otherwise I use explode.
$data = str_replace(array("\r\n", "\r", "\n"), "", trim($postgresArray,'{}'));
if (strpos($data, '"') === 0) {
$data = '[' . $data . ']';
$result = json_decode($data);
} else {
$result = explode(',', $data);
}
If you have control of the query that's hitting the database, why don't you just use unnest() to get the results as rows instead of Postgres-arrays? From there, you can natively get a PHP-array.
$result = pg_query('SELECT unnest(myArrayColumn) FROM someTable;');
if ( $result === false ) {
throw new Exception("Something went wrong.");
}
$array = pg_fetch_all($result);
This sidesteps the overhead and maintenance-issues you'd incur by trying to convert the array's string-representation yourself.
I can see you are using explode(',', trim($pgArray, '{}'));
But explode is used to Split a string by string (and you are supplying it an array!!). something like ..
$string = "A string, with, commas";
$arr = explode(',', $string);
What are you trying to do with array? if you want to concatenate have a look on implode
OR not sure if it is possible for you to specify the delimiter other than a comma? array_to_string(anyarray, text)
Postgresql arrays look like this: {1,2,3,4}
You can just simply replace first { and last } with [ and ] respectively and then json_decode that.
$x = '{1,2,3,4}';
$y = json_decode('[' . substr($x, 1, -1) . ']'); // [1, 2, 3, 4]
To cast back the other way would be mirror opposite:
$y = [1, 2, 3, 4];
$x = '{' . substr(json_encode($y), 1, -1) . '}';
A simple and fast function for converting deep PostgreSQL array string to JSON string without using pg connection.
function pgToArray(string $subject) : array
{
if ($subject === '{}') {
return array();
}
$matches = null;
// find all elements;
// quoted: {"1{\"23\"},abc"}
// unquoted: {abc,123.5,TRUE,true}
// and empty elements {,,}
preg_match_all( '/\"((?<=\\\\).|[^\"])*\"|[^,{}]+|(?={[,}])|(?=,[,}])/', $subject,$matches,PREG_OFFSET_CAPTURE);
$subject = str_replace(["{","}"],["[","]"],$subject); // converting delimiters to JSON
$matches = array_reverse($matches[0]);
foreach ($matches as $match) {
$item = trim($match[0]);
$replace = null;
if ((strpos($item,"{") !== false) || (strpos($item,"}") !== false)) {
// restoring replaced '{' and '}' inside string
$replace = $match[0];
} elseif (in_array($item,["NULL","TRUE","FALSE"])) {
$replace = strtolower($item);
} elseif ($item === "" || ($item[0] !== '"' && !in_array($item,["null","true","false"]) && !is_float($item))) {
$replace = '"' . $item . '"'; // adding quotes to string element
}
if ($replace) { // concatenate modified element instead of old element
$subject = substr($subject, 0, $match[1]) . $replace . substr($subject, $match[1] + strlen($match[0]));
}
}
return json_decode($subject, true);
}

Finding tags in query string with regular expression

I have to set some routing rules in my php application, and they should be in the form
/%var/something/else/%another_var
In other words i beed a regex that returns me every URI piece marked by the % character, String marked by % represent var names so they can be almost every string.
another example:
from /%lang/module/controller/action/%var_1
i want the regex to extract lang and var_1
i tried something like
/.*%(.*)[\/$]/
but it doesn't work.....
Seeing as it's routing rules, and you may need all the pieces at some point, you could also split the string the classical way:
$path_exploded = explode("/", $path);
foreach ($path_exploded as $fragment) if ($fragment[0] == "%")
echo "Found $fragment";
$str='/%var/something/else/%another_var';
$s = explode("/",$str);
$whatiwant = preg_grep("/^%/",$s);
print_r($whatiwant);
I don’t see the need to slow down your script with a regex … trim() and explode() do everything you need:
function extract_url_vars($url)
{
if ( FALSE === strpos($url, '%') )
{
return $url;
}
$found = array();
$parts = explode('/%', trim($url, '/') );
foreach ( $parts as $part )
{
$tmp = explode('/', $part);
$found[] = ltrim( array_shift($tmp), '%');
}
return $found;
}
// Test
print_r( extract_url_vars('/%lang/module/controller/action/%var_1') );
// Result:
Array
(
[0] => lang
[1] => var_1
)
You can use:
$str = '/%lang/module/controller/action/%var_1';
if(preg_match('#/%(.*?)/[^%]*%(.*?)$#',$str,$matches)) {
echo "$matches[1] $matches[2]\n"; // prints lang var_1
}

Categories