I have a path that I want to check for in a url. How would I isolate
'pages/morepages/'
http://www.mypage.com/pages/morepages/
I've tried running a parse url function on my url and then I get the path. I don't know how to access that key in that array though. For example..
$url = 'http://www.mypage.com/pages/morepages/';
print_r(parse_url($url));
if ($url['path'] == '/pages/morepages/') {
echo 'This works.';
};
I want to run an if conditional on if that path exists, but I am having trouble accessing it.
If you're just looking for one string within another, strpos() will work pretty well.
echo strpos( $url, $path ) !== false ? 'Exists' : 'Does Not Exist' ;
something like find in string ?
if ( strpos($url['path'], '/pages/morepages/') !== false ){
//echo "this works";
}
Here you go
$url = 'http://www.mypage.com/pages/morepages/';
if (strpos($url, '/pages/morepages/') !== false) {
echo "found";
} else {
echo "not found";
}
You can simply use
if (parse_url($url['path'], PHP_URL_PATH) == '/pages/morepages/') {
echo 'This works.';
} // No semicolon
It's probably better to use strpos() though, which is a LOT faster.
Just assign function's result to any variable:
$parts = parse_url($url);
if ($parts['path'] == '/pages/morepages') {
}
Parse_url needs to return something to a new array variable. So use:
$parsedUrl = parse_url($url));
if ($parsedUrl['path'] == '/pages/morepages/') {
echo 'This works.';
};
You are not assigning the output of parse_url to a variable. $url is still equal to the string (parse_url returns an array, it doesn't modify the string passed in).
$url = parse_url($url);
Related
I meet a strange thing with the PHP function strpos().
I have a function that check if a passed string is found in a txt file.
I can display the content of the file line by line but the strpos() doesn't return a value (nothing in fact). var_dump() of the return empty.
Can someone see a mistake, because I am lost.
Thank you in advance.
My function :
function checkIfExist($string)
{
$path = "\\\\server\\temp\\test.txt";
$file = file($path);
foreach( $file as $line )
{
echo $line; //display the string in this line
$found = strpos($file,$string);
echo $found; //display nothing, not even a boolean/int
}
return $found;
}
Try to change $found = strpos($file,$string); to $found = strpos($line,$string);
Echoing a false boolean won't show up. Try changing it to a var_dump and you will see that it's a boolean set to false.
Sorry, I have made a mistake when writen the code, this is the good one :
function checkIfExist($string)
{
$path = "\\\\server\\temp\\test.txt";
$file = file($path);
foreach( $file as $line )
{
echo $line; //display the string in this line
$found = strpos($line,$string);
echo $found; //display nothing, not even a boolean/int
var_dump($found); //display boolena(false) for all the test even if the
string is well present once.
}
return $found;
}
This code give the same result
foreach( $file as $line )
{
echo $line; //display "www.google.be"
echo $string; //also display "www.google.be"
//but when I then if the line contain the string, the function doesn't find
it!!!
$pos = stripos($line,$hostname);
var_dump($pos); // FALSE for all the test
}
I have done this thes in other code, and I never had this issue.
Setup debugging, so you see the values of strpos. If debugging cannot be arranged than vardump $line and $string. You will probably get unexpected values. Also try avoiding typecasting-issues. Perhaps this will work better.
if (strpos($line,$string) != false){...}else{...}
I am trying to use the following code to check if the current URL is within an array.
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (strpos($url, $reactfulPages) == true) {
echo "URL is inside list";
}
I think the way I have set up the array is incorrect as the following code (checking for one URL) works fine..
if (strpos($url,'url-one') == true) { // Check if URL contains "landing-page"
}
Can anyone help me out?
The array is fine, the functions to check is not the right way. The strpos() function is for checking the string position(s).
The right way to check if something is in your array you can use the in_array() function.
<?php
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if(in_array($url, $reactfulPages)) {
echo "The URL is in the array!";
// Continue
}else{
echo "The URL doesn't exists in the array.";
}
?>
I hope this will work for you.
The function strpos() looks for a substring within a string, and returns the the position of the substring if it is found. That is why your last example works.
If you want to check whether something exists in an array, you should use the in_array() function, like so:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (in_array($url, $reactfulPages) == true) {
echo "URL is inside list";
}
However, since you're comparing URL's, I'm assuming you want to check whether the URL contains one of the strings from the array, not necessarily matching them as a whole.
In this case, you will need to write your own function, which could look like this:
function contains_any($string, $substrings) {
foreach ($substrings as $match) {
if (strpos($string, $match) >= 0) {
// A match has been found, return true
return true;
}
}
// No match has been found, return false
return false;
}
You can then apply this function to your example:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (contains_any($url, $reactfulPages)) {
echo "URL is inside list";
}
Hope this helps.
I want to write a PHP script which will first detect URL's and see if they have sub dir or not, if they are simple URL like site.com then it would write 1 in one of the DB's table but if the URL is something like this site.com/images or site.com/images/files then it should'nt do the query..
EDIT: Answer by Mob it works but doesnt work if there are more than one url
$url = "http://lol.com";
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
echo "yeah";
} else {
echo "nah";
}
Use parse_url
$url = "http://lol.com";
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
echo "yeah";
} else {
echo "nah";
}
EDIT:
To parse multiple urls;
Store the urls in an array.
Use a loop to iterate over the array while passing the values to a function that performs the check
Here:
<?php
$arr = array("http://google.com",
"http://google.com/image/",
"http://flickr.com",
"http://flickr.com/image" );
foreach ($arr as $val){
echo $val." ". check($val)."\n";
}
function check ($url){
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
return "true";
} else {
return "false";
}
}
?>
The output is :
http://google.com false
http://google.com/image/ true
http://flickr.com false
http://flickr.com/image true
Try strpos()
Syntax: strpos($haystack, $needle)
You could use something like:
if (!strpos($url, '/'))
{
do_query();
}
edit
Remember to strip the slashes in http://, of course.
$_SERVER is what you need. I'll let you google it.
How can I write a function to check whether the provided URLs is youtube or vimeo?
For instance, I have this two URLs that I store in a database as strings,
http://vimeo.com/24456787
http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded
If the URL is youtube then I will rewrite the URL to,
http://www.youtube.com/embed/rj18UQjPpGA?rel=0&wmode=transparent
If the URL is vimeo then I will rewrite this URL to,
http://vimeo.com/moogaloop.swf?clip_id=24456787
Thanks.
Use the parse_url function to split the URL up and then just do your normal checks
$url = 'http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded';
$parsed = parse_url($url);
Will give you this array
array
'scheme' => string 'http' (length=4)
'host' => string 'www.youtube.com' (length=15)
'path' => string '/watch' (length=6)
'query' => string 'v=rj18UQjPpGA&feature=player_embedded' (length=37)
I recently wrote this function to do exactly this, hopefully it's useful to someone:
/**
* [determineVideoUrlType used to determine what kind of url is being submitted here]
* #param string $url either a YouTube or Vimeo URL string
* #return array will return either "youtube","vimeo" or "none" and also the video id from the url
*/
public function determineVideoUrlType($url) {
$yt_rx = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/';
$has_match_youtube = preg_match($yt_rx, $url, $yt_matches);
$vm_rx = '/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/';
$has_match_vimeo = preg_match($vm_rx, $url, $vm_matches);
//Then we want the video id which is:
if($has_match_youtube) {
$video_id = $yt_matches[5];
$type = 'youtube';
}
elseif($has_match_vimeo) {
$video_id = $vm_matches[5];
$type = 'vimeo';
}
else {
$video_id = 0;
$type = 'none';
}
$data['video_id'] = $video_id;
$data['video_type'] = $type;
return $data;
}
As others have noted in the comments, this is a quick and dirty solution that does not handle edge cases well. If the url contains "youtube"(example.com/youtube) it will return a false positive. The parse_url() solution mentioned below is a much more robust solution.
Regular expressions work well for this type of thing, but often strpos or substr are faster performance wise. Check out the PHP documentation for preg_match(). Below the examples there is a note for exactly this thing.
Here is prototype code:
function videoType($url) {
if (strpos($url, 'youtube') > 0) {
return 'youtube';
} elseif (strpos($url, 'vimeo') > 0) {
return 'vimeo';
} else {
return 'unknown';
}
}
Obviously returning a string isn't the best idea, but you get the point. Substitute your own business logic.
You can use preg_match():
$u1="http://vimeo.com/24456787";
$u2="http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded";
if(preg_match('/http:\/\/(www\.)*vimeo\.com\/.*/',$u1)){
// do vimeo stuff
echo "Vimeo URL found!\n";
}
if(preg_match('/http:\/\/(www\.)*youtube\.com\/.*/',$u2)){
// do youtube stuff
echo "YouTube URL found!\n";
}
Since all you want to do is check for the presence of a string, use stripos. If it doesn't have youtube.com or vimeo.com in it, the url is malformed, right? stripos is case insensitive, too.
if(stripos($url,'youtu')===false){
//must be vimeo
} else {
//is youtube
}
You can try my solution:
function checkServer( $domains=array(), $url ) {
foreach ( $domains as $domain ) {
if ( strpos($url, $domain ) > 0) {
return true;
} else {
return false;
}
}
}
Use:
if( checkServer(array("youtube.com","youtu.be"), $url ) ) {
//is Youtube url
}
elseif( checkServer(array("vimeo.com"), $url ) ) {
//is Vimeo
}
elseif ( checkServer(array("any domain"), $url ) ) {
//is Any Domain
}else {
//unknow domain
}
Use regular expressions. What language are you using?
Edit: noticed your tag was php. It would be something like this:
<?php
// get host name from URL
preg_match('#^(?:http://)?([^/]+)#i',
"http://www.youtube.com/index.html", $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo {$matches[0]}\n"; //youtube.com
?>
You can try this
<?php
if (strpos($videourl, 'youtube') > 0) {
echo 'This is a youtube video';
}
?>
why is the following php code not working:
$string = "123";
$search = "123";
if(strpos($string,$search))
{
echo "found";
}else{
echo "not found";
}
as $search is in $string - shouldn't it be triggered as found?
This is mentioned in the Manual: strpos()
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
In your case the string is found at the index 0 and in php 0 == false
The solution is to just use the strict comparator
echo strpos($string,$search) === false
? "not found"
: "found";
Another one
echo is_int(strpos($string,$search))
? "found"
: "not found";
Or something ... lets say interesting :D Just for illustration. I don't recommend this one.
echo strpos('_' . $string,$search) // we just shift the string 1 to the right
? "found"
: "not found";
This is happening because the search string is being found at position 0.
Try
if(strpos($string,$search) !== FALSE)
instead of
if(strpos($string,$search))
strpos returns the first offset where $search was found - 0. 0 in turn evaluates to false. Therefore the if fails.
If $search was not found, strpos returns FALSE. First check the return value for !== FALSE, and then check the offset.
Thanks to everyone who pointed this out in the comments.
see: http://php.net/manual/en/function.strpos.php
From the manual:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator
for testing the return value of this
function.
In your example, you should use
$string = "123";
$search = "123";
if ( false !== strpos( $string, $search ) ) {
echo "found";
} else {
echo "not found";
}
strpos returns the numeric position of the string you want to search for if it finds it. So in your case, you want to be doing this instead:
$search = "123";
$string = "123";
if (strpos($string,$search)===false) { echo "not found"; }
else { echo "found"; }
basically it returns a false if it doesn't find your string
You can use this:
<?php
$string = "123";
$find = "123";
$strpos = strpos($string, $find);
if($strpos || $strpos === (int)0) {
echo "Found it!";
} else {
echo "Not Found!";
}
?>
Well documented issue explained here. strpos is simply returning '0'