I have url like https://in.pinterest.com/sridharposnic/restinpeace/.
I want url directories without domain in php array.
Example:-
$array[0] = 'sridharposnic';
$array[1] = 'restinpeace';
How we can extract these ?
You can use parse_url() and explode():
$url = 'https://in.pinterest.com/sridharposnic/restinpeace/';
$parsed = parse_url( $url );
$chunks = explode( '/', trim($parsed['path'],'/') );
print_r( $chunks );
Will print:
Array
(
[0] => sridharposnic
[1] => restinpeace
)
Related
This is the initial string:-
NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n
This is my solution although the "=" in the end of the string does not appear in the array
$env = file_get_contents(base_path() . '/.env');
// Split string on every " " and write into array
$env = preg_split('/\s+/', $env);
//create new array to push data in the foreach
$newArray = array();
foreach($env as $val){
// Split string on every "=" and write into array
$result = preg_split ('/=/', $val);
if($result[0] && $result[1])
{
$newArray[$result[0]] = $result[1];
}
}
print_r($newArray);
This is the result I get:
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )
But I need :
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )
You can use the limit parameter of preg_split to make it only split the string once
http://php.net/manual/en/function.preg-split.php
you should change
$result = preg_split ('/=/', $val);
to
$result = preg_split ('/=/', $val, 2);
Hope this helps
$string = 'NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n';
$strXlate = [ 'NAME=' => '"NAME":"' ,
'LOCATION=' => '","LOCATION":"',
'SECRET=' => '","SECRET":"' ,
'\n' => '' ];
$jsonified = '{'.strtr($string, $strXlate).'"}';
$array = json_decode($jsonified, true);
This is based on 1) translation using strtr(), preparing an array in json format and then using a json_decode which blows it up nicely into an array...
Same result, other approach...
You can also use parse_str to parse URL syntax-like strings to name-value pairs.
Based on your example:
$newArray = [];
$str = file_get_contents(base_path() . '/.env');
$env = explode("\n", $str);
array_walk(
$env,
function ($i) use (&$newArray) {
if (!$i) { return; }
$tmp = [];
parse_str($i, $tmp);
$newArray[] = $tmp;
}
);
var_dump($newArray);
Of course, you need to put some sanity check in the function since it can insert some strange stuff in the array like values with empty string keys, and whatnot.
I have an array that looks like the following...
$urls = array(
"http://www.google.com",
"http://www.google.com/maps",
"http://www.google.com/mail",
"https://drive.google.com/help",
"https://www.youtube.com",
"https://www.youtube.com/feed/subscriptions",
"https://www.facebook.com/me",
"https://www.facebook.com/me/friends"
);
I find this hard to explain but I want to break this array down to only show the lowest path for each domain with no duplicates, so it looks like this...
$urls = array(
"http://www.google.com",
"https://drive.google.com/help",
"https://www.youtube.com",
"https://www.facebook.com/me"
);
This can be achieved by walking through the array and inspecting the host key by using parse_url(). The following logic will give your desired result.
$output = array();
//Sort the array by character length
usort($urls, function($a, $b) {
return strlen($a)-strlen($b);
});
array_walk($urls, function($url) use (&$output) {
//Parse the URL to get its components
$parsed_url = parse_url($url);
//See if we've already added the host to our final array
if( array_key_exists($parsed_url['host'], $output) === FALSE ) {
//We haven't, so we can now add the url to our final array
$output[$parsed_url['host']] = $url;
}
});
https://eval.in/415655
try this,
$urls = array(
"http://www.google.com",
"http://www.google.com/maps",
"http://www.google.com/mail",
"https://drive.google.com/help",
"https://www.youtube.com",
"https://www.youtube.com/feed/subscriptions",
"https://www.facebook.com/me",
"https://www.facebook.com/me/friends"
);
$temp = array();
$res = array();
usort($urls, function($a, $b) {
return strlen($a)-strlen($b);
});//sort the array based string length
foreach($urls as $url){
$str = preg_replace('#^https?://#', '', $url);
$strarray = explode("/", $str);
if(!in_array($strarray[0], $temp)){
$temp[] = $strarray[0];
$res[] = $url;
}
}
echo"<pre>";
print_r($res);
echo"</pre>";
output:
Array
(
[0] => http://www.google.com
[1] => https://www.youtube.com
[2] => https://www.facebook.com/me
[3] => https://drive.google.com/help
)
I have a string like this:
$url = '/controller/method/para1/para2/';
Expected output:
Array(
[0] => 'controller',
[1] => 'method',
[2] => array(
[0] => 'para1',
[1] => 'para2'
)
)
I am trying to build a regex to achieve this but not able to construct the pattern properly.
Please assist.
I tried to use explode function to split,
$split_url = explode('/',$url);
$controller = $split_url[1];
$method = $split_url[2];
unset($split_url[0]);
unset($split_url[1]);
unset($split_url[2]);
$para = $split_url;
But this is really not a great way of doing this and is prone to errors.
whithout regex:
$url = '/controller/method/para1/para2/para3/';
$arr = explode('/', trim($url, '/'));
$result = array_slice($arr, 0, 2);
$result[] = array_slice($arr, 2);
print_r($result);
Note: if you need to always have parameters at the same index (even if there is no method or parameters), you can change $result[] = array_slice($arr, 2); to $result[2] = array_slice($arr, 2);
Here's a slightly nasty method using explode:
$url = '/controller/method/para1/para2/para3/';
# get rid of leading and trailing slashes
$url = trim($url, '/');
$arr = explode('/', $url);
$results = array( $arr[0], $arr[1], array_slice($arr, 2) );
print_r($results);
Output:
Array
(
[0] => controller
[1] => method
[2] => Array
(
[0] => para1
[1] => para2
[2] => para3
)
)
It will work for any number of para elements.
And just to show that regexs are not scary, they're lovely fluffy friendly things, here's a regex version:
preg_match_all("/\/(\w+)/", $url, $matches);
$arr = $matches[1];
$results = array( $arr[0], $arr[1], array_slice($arr, 2) );
It's actually very easy to match this URL -- just search for / followed by alphanumeric characters (\w+).
How about something like:
$url = '/controller/method/para1/para2/para3/';
$regex = '~^/([^/]+)/([^/]+)/(?:(.*)/)?$~';
if(preg_match($regex, $url, $matches)) {
$controller = $matches[1];
$method = $matches[2];
$parameters = explode('/', $matches[3]);
}
This will capture 3 segments separated by a leading/trailing /. The 3rd segment of parameters can then be split with explode(). To get the array exactly like in your question:
$array = array($controller, $method, $parameters);
// Array
// (
// [0] => controller
// [1] => method
// [2] => Array
// (
// [0] => para1
// [1] => para2
// [2] => para3
// )
// )
An alterate way of thinking about this is to actually parse your route to determine the controller and then pass the remaining route components off to the controller to determine what to do.
$url = '/controller/method/para1/para2/para3/';
$route_parts = explode('/', $url, '/')); // we don't need leading and trailing forward slashes
$controller_str = array_shift($route_parts);
$method_str = array_shift($route_parts);
// instantiate controller object be some means (a factory pattern shown here for demo purposes)
$controller = controllerFactory::getInstance($controller_str);
// set method on controller
$controller->setMethod($method_str);
// pass parameters to controller
$controller->setParams($route_parts);
// do whatever with controller
$controller->execute();
I have an array with a list of all controllers in my application:
$controllerlist = glob("../controllers/*_controller.php");
How do I strip ../controllers/ at the start and _controller.php at the end of each array element with one PHP command?
As preg_replace can act on an array, you could do:
$array = array(
"../controllers/test_controller.php",
"../controllers/hello_controller.php",
"../controllers/user_controller.php"
);
$array = preg_replace('~../controllers/(.+?)_controller.php~', "$1", $array);
print_r($array);
output:
Array
(
[0] => test
[1] => hello
[2] => user
)
Mapping one array to another:
$files = array(
'../controllers/test_controller.php',
'../controllers/hello_controller.php'
);
$start = strlen('../controllers/');
$end = strlen('_controller.php') * -1;
$controllers = array_map(
function($value) use ($start, $end) {
return substr($value, $start, $end);
},
$files
);
var_dump($controllers);
I'm not sure how you defined "command", but I doubt there is a way to do that with one simple function call.
However, if you're simply wanting it to be compact, here's a simple way of doing it:
$controllerlist = explode('|||', str_replace(array('../controllers/', '_controller.php'), '', implode('|||', glob("../controllers/*_controller.php"))));
It's a bit dirty, but it gets the job done in a single line.
One command without searching and replacing? Yes you can!
If I'm not missing something grande, what about keeping it simple and chopping 15 characters from the start and the end using the substr function:
substr ( $x , 15 , -15 )
Since glob will always give you strings with that pattern.
Example:
// test array (thanks FruityP)
$array = array(
"../controllers/test_controller.php",
"../controllers/hello_controller.php",
"../controllers/user_controller.php" );
foreach($array as $x){
$y=substr($x,15,-15); // Chop 15 characters from the start and end
print("$y\n");
}
Output:
test
hello
user
No need for regex in this case unless there can be variations of what you mentioned.
$array = array(
"../controllers/test_controller.php",
"../controllers/hello_controller.php",
"../controllers/user_controller.php"
);
// Actual one liner..
$list = str_replace(array('../controllers/', '_controller.php'), "", $array);
var_dump($array);
This will output
array (size=3)
0 => string 'test' (length=4)
1 => string 'hello' (length=5)
2 => string 'user' (length=4)
Which is (I think) what you asked for.
If you have an array like this :
$array = array( "../controllers/*_controller.php",
"../controllers/*_controller.php");
Then array_map() help you to trim the unnecessary string.
function trimmer( $string ){
return str_replace( "../controllers/", "", $string );
}
$array = array( "../controllers/*_controller.php",
"../controllers/*_controller.php");
print_r( array_map( "trimmer", $array ) );
http://codepad.org/VO6kyVOa
to strip 15 chars at the start and 15 at the end of each arrayelement in one command:
$controllerlist = substr_replace(
substr_replace(
glob("../controllers/*_controller.php"),'',-15
),'',0,15
)
preg_replace accepts an array as argument too:
$before = '../controllers/';
$after = "_controller.php";
$preg_str = preg_quote($before,"/").'(.*)'.preg_quote($after,"/");
$controllerlist = preg_replace('/^'.$preg_str.'$/', '\1', glob("$before*$after"));
I know you can easily get a parameter from the page you're currently on, but can you easily do the same from any URL string?
I need to grab the "id" parameter out of a string like https://market.android.com/details?id=com.zeptolab.ctr.paid?t=W251bGwsMSwxLDIxMiwiY29tLnplcHRvbGFiLmN0ci5wYWlkIl0.
How can I do this with PHP? Is there a built-in function, or do I have to use regex?
You could use combination of parse_url and parse_str:
$url = 'https://market.android.com/details?id=com.zeptolab.ctr.paid?t=W251bGwsMSwxLDIxMiwiY29tLnplcHRvbGFiLmN0ci5wYWlkIl0';
$arr = parse_url($url);
parse_str($arr['query']);
echo $id; //com.zeptolab.ctr.paid?t=W251bGwsMSwxLDIxMiwiY29tLnplcHRvbGFiLmN0ci5wYWlkIl0
Yes you can.
parse_url()
From the PHP docs:
<?php
$url = 'http://username:password#hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
The above example will output:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path
There's parse_url():
function extractGETParams($url)
{
$query_str = parse_url($url, PHP_URL_QUERY);
$parts = explode('&', $query_str);
$return = array();
foreach ( $parts as $part )
{
$param = explode('=', $part);
$return[$param[0]] = $param[1];
}
return $return;
}
$url = 'http://username:password#hostname/path?arg=value&arg2=value2#anchor';
var_dump( extractGETParams($url) );
On Codepad.org: http://codepad.org/mHXnOYlc
You can use parse_str(), and then access the variable $id.