I have this code, the part I am looking for is the number from the url 1538066650683084805
I use this example
$tweet_url = 'https://twitter.com/example/status/1538066650683084805'
$arr = explode("/", $tweet_url);
$tweetID = end($arr);
Which works however sometimes on phones, When people copy and paste the url it has parameters on the end of it like this;
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
When a URL is exploded with the URL above the code doesn't work, how do I get the number 1538066650683084805 in both uses.
Thanks so much.
I would suggest using parse_url to get just the path, then separate that out:
$url = parse_url('https://twitter.com/example/status/1538066650683084805?q=2&t=1');
/*
[
"scheme" => "https",
"host" => "twitter.com",
"path" => "/example/status/1538066650683084805",
"query" => "q=2&t=1",
]
*/
$arr = explode("/", $url['path']);
$tweetID = end($arr);
I would explode first on the question mark and just look at the index 0 .. THEN explode the slash ...
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweet_url = explode('?', $tweet_url)[0];
$arr = explode("/", $tweet_url);
$tweetID = end($arr);
If the question mark does not exist -- It will still return the full URL in $tweet_url = explode('?', $tweet_url)[0]; so it's harmless to have it there.
And this is just me .. But I would write it this way:
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweetID = end(
explode("/",
explode('?', $tweet_url)[0]
)
);
echo $tweetID . "\n\n";
So lets say I have a link like this:
http://mywebsite.com/profile/alexkvazos/
I would like to explode the url and get this:
$uri = array('profile','alexkvazos');
What is the easiest approach to this?
try
// if the url is http://www.example.com/foo/bar/wow
function getUriSegments() {
return explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
}
print_r(getUriSegments()); //returns array(0=>'foo', 1=>'bar', 2=>'wow')
Source :- http://www.timwickstrom.com/server-side-code/php/php-get-uri-segments/
Use parse_url()
$path_parts = parse_url('http://mywebsite.com/profile/alexkvazos/');
$uri = explode('/',trim($path_parts['path'],'/'));
print_r($uri);
Working Demo
You could use this piece of code:
<?php
$url = 'http://mywebsite.com/profile/alexkvazos/';
$url = rtrim($url,'/'); // lose the trailing slash
$urlArr = explode("/", $url );
$urlArr = array_reverse( $urlArr );
echo $urlArr[0];
?>
I wouldn't use parse_url, I would just use preg_split like this:
$segments = preg_split('#/#', $_SERVER['REQUEST_URI']);
$final = array();
foreach($segments as $key => $value) {
if($value != '') {
$final[] = $value;
}
}
var_dump($final);
This question already has answers here:
filter values from an array similar to SQL LIKE '%search%' using PHP
(4 answers)
Closed last month.
I have the following Array :
Array
{
[0]=>"www.abc.com/directory/test";
[1]=>"www.abc.com/test";
[2]=>"www.abc.com/directory/test";
[3]=>"www.abc.com/test";
}
I only want the items that have something in middle in URL like /directory/ and unset the items that do not have that.
Output should be like:
Array
{
[0]=>"www.abc.com/directory/test";
[1]=>"www.abc.com/directory/test";
}
An example without closures. Sometimes you just need to understand the basics first, before you can move on to the neater stuff.
$newArray = array();
foreach($array as $value) {
if ( strpos( $value, '/directory/') ) {
$newArray[] = $value;
}
}
Try using array_filter this:
$result = array_filter($data, function($el) {
$parts = parse_url($el);
return substr_count($parts['path'], '/') > 1;
});
If you have something inside path will allways contain at least 2 slashes.
So for input data
$data = Array(
"http://www.abc.com/directory/test",
"www.abc.com/test",
"www.abc.com/directory/test",
"www.abc.com/test/123"
);
you output will be
Array
(
[0] => http://www.abc.com/directory/test
[2] => www.abc.com/directory/test
[3] => www.abc.com/test/123
)
A couple of approaches:
$urls = array(
'www.abc.com/directory/test',
'www.abc.com/test',
'www.abc.com/foo/directory/test',
'www.abc.com/foo/test',
);
$matches = array();
// if you want /directory/ to appear anywhere:
foreach ($urls as $url) {
if (strpos($url, '/directory/')) {
$matches[] = $url;
}
}
var_dump($matches);
$matches = array();
// if you want /directory/ to be the first path:
foreach ($urls as $url) {
// make the strings valid URLs
if (0 !== strpos($url, 'http://')) {
$url = 'http://' . $url;
}
$parts = parse_url($url);
if (isset($parts['path']) && substr($parts['path'], 0, 11) === '/directory/') {
$matches[] = $url;
}
}
var_dump($matches);
<?php
$array = Array("www.abc.com/directory/test",
"www.abc.com/test",
"www.abc.com/directory/test",
"www.abc.com/test",
);
var_dump($array);
array_walk($array, function($val,$key) use(&$array){
if (!strpos($val, 'directory')) {
unset($array[$key]);
}
});
var_dump($array);
php >= 5.3.0
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']
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
}