I would like to figure out, how to check if the second to last character of a string is numeric.
My string is:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
The URL is something like: http://www.domain.com/2/,http://www.domain.com/3/ and so on..
Is it possible to figure out if a number exists at the end of the URL before the last back slash / ?
Something like:
if (is_numeric($url, second-to-last-character)) {
// Do real stuff
} else {
// Do whatever
}
What about regexes ?
if (!preg_match('#/\d+/?$#', $url))
// There is no numeric at the end, abort !
I propose this because you won't know how many digits your id will have, so you can't just test the second-to-last character.
$fullurl = explode('/',$_SERVER['SCRIPT_NAME']);
$last = $fullurl[count($fullurl)-1];
//echo $last;
if(is_int($last))
echo "integer";
else
echo "Not integer";
You want to use substr. You can use this to get the second to last character.
http://php.net/manual/en/function.substr.php
is_numeric(substr($url, -2, 1);
if (is_numeric(substr($url, -2,1) ) {
should do you, You dont need the regex
use substr
if(is_numeric(substr($url,-2,1))){
//dosomething
}else{
echo "Invalid URL!";
}
in substr, the first parameter is the string, the second one is the offset, if the offset is negative, it will start at the end and go backwards, and the last one is the length. If not specified, it will go to the end of the string. So if you wanted to get the last tow characters, you would do substr($url,-2)
$url='http://www.domain.com/2/,http://www.domain.com/3/';
if(is_numeric (substr($url,-2,1))){
echo "This is number";
}else{
echo "This is not number";
}
I don't want to get offtopic, but when i'm dealing with URLs usually i delete ending slashes using
$url = rtrim($url, '/');
http://www.php.net/manual/en/function.rtrim.php
Usually you won't need that slash and it'll be messy when exploding the URL. You can use the substr() function as mentioned by previous answers to get the last character of the string then. AFAIK the substr() function is faster than using regular expressions for such a simple task.
if (is_numeric(substr($url, -1)) {}
edit
i just realized that if you are dealing with values > 9 you will be in trouble.
Better get the whole number as mentioned in another answer. If you prefer strange looking code with slightly better performance you can use that one instead of explode():
$value = strrev(strtok(strrev($url), '/'));
if (is_numeric($value)) {}
Related
I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon
I have a string with 3 block parameters (words, digits, slashes) and i need to separate it and print only last block parameters. I do this:
<?php
$howmuch="17шт / 119ml / 255грн";
echo preg_replace("/(\\d\\w\\ / )(\\d\\w\\ / )(\\d\\w\\ / )$/i", "$3", $howmuch);
?>
I need to print only 255грн, but my script do nothing. Please help me to fix a problem. Thank you to all.
If the format is fixed, you may get the value without any regex using
explode(" / ", $howmuch)[2]
See the PHP demo. It will split the string with space-/-space and get you the third element of the resulting array.
Alternatively, you may extract a number with грн after it using a preg_match operation (this approach lets you find the match regardless of how many / there are before or after the match):
$howmuch="17шт / 119ml / 255грн";
if (preg_match("/\d+\s*грн/ui", $howmuch, $results)) {
echo $results[0];
}
See the PHP demo.
If the value can contain a fractional part, you may use "/\d+(?:[.,]\d+)?\s*грн/ui" where (?:[.,]\d+)? matches an optional sequence of a . or , followed with 1+ digits.
Why not keep it simple and understandable, for instance, like this:
$howMuch = '17шт / 119ml / 255грн';
$blocks = explode('/',$howMuch);
echo $blocks[2];
This doesn't need much explaining, or working out why it does what it does.
All regex free options:
echo explode('/', $howMuch)[2];
if you need to ensure string has three sections
if (substr_count($howmuch, '/') > 1) {
echo explode('/', $howMuch)[2];
}
if you are on a php version prior to 5.4
$chunks = explode('/', $howMuch);
echo $chunks[2];
i am trying to handle from server side to check the string is in correct format or not for example
$string = "9000010000,9100011000,9000020000 // Its correct pattern
$string = "9000010000,9100011000,9000020000, // Its WRONG Reason comma in last place
$string = ",9000010000,9100011000,9000020000, // Its WRONG Reason comma in first place
$string = ",9000010000,9100011000,,9000020000, // Its WRONG Reason ,,
$string = "9000010000,9100011,9000020000, // Its WRONG because Middle no. is not 10 digit
i already did client side validation through JavaScript using this code
var listIsOk=/^(\d{10},)*\d{10}$/.test(contact_list);
if(listIsOk==true){
alert("success"
}
else {
alert("string is wrong")
}
i want to know how i can achieve this on php thank you in advance
if (preg_match('/^(\d{10},)*\d{10}$/', $string)) {
echo 'success';
} else {
echo 'string is wrong';
}
Start by looking into the php function explode(), which will allow you to split your string into an array of phone numbers. From there you'll need to loop through and look at each one to determine if it's correct.
I would like to know how I could find out in PHP if a variable only contains 1 word. It should be able to recognise: "foo" "1326" ";394aa", etc.
It would be something like this:
$txt = "oneword";
if($txt == 1 word){ do.this; }else{ do.that; }
Thanks.
I'm assuming a word is defined as any string delimited by one space symbol
$txt = "multiple words";
if(strpos(trim($txt), ' ') !== false)
{
// multiple words
}
else
{
// one word
}
What defines one word? Are spaces allowed (perhaps for names)? Are hyphens allowed? Punctuation? Your question is not very clearly defined.
Going under the assumption that you just want to determine whether or not your value contains spaces, try using regular expressions:
http://php.net/manual/en/function.preg-match.php
<?php
$txt = "oneword";
if (preg_match("/ /", $txt)) {
echo "Multiple words.";
} else {
echo "One word.";
}
?>
Edit
The benefit to using regular expressions is that if you can become proficient in using them, they will solve a lot of your problems and make changing requirements in the future a lot easier. I would strongly recommend using regular expressions over a simple check for the position of a space, both for the complexity of the problem today (as again, perhaps spaces aren't the only way to delimit words in your requirements), as well as for the flexibility of changing requirements in the future.
Utilize the strpos function included within PHP.
Returns the position as an integer. If needle is not found, strpos()
will return boolean FALSE.
Besides strpos, an alternative would be explode and count:
$txt = trim("oneword secondword");
$words = explode( " ", $txt); // $words[0] = "oneword", $words[1] = "secondword"
if (count($words) == 1)
do this for one word
else
do that for more than one word assuming at least one word is inputted
I am trying to validate a Youtube URL using regex:
preg_match('~http://youtube.com/watch\?v=[a-zA-Z0-9-]+~', $videoLink)
It kind of works, but it can match URL's that are malformed. For example, this will match ok:
http://www.youtube.com/watch?v=Zu4WXiPRek
But so will this:
http://www.youtube.com/watch?v=Zu4WX£&P!ek
And this wont:
http://www.youtube.com/watch?v=!Zu4WX£&P4ek
I think it's because of the + operator. It's matching what seems to be the first character after v=, when it needs to try and match everything behind v= with [a-zA-Z0-9-]. Any help is appreciated, thanks.
To provide an alternative that is larger and much less elegant than a regex, but works with PHP's native URL parsing functions so it might be a bit more reliable in the long run:
$url = "http://www.youtube.com/watch?v=Zu4WXiPRek";
$query_string = parse_url($url, PHP_URL_QUERY); // v=Zu4WXiPRek
$query_string_parsed = array();
parse_str($query_string, $query_string_parsed); // an array with all GET params
echo($query_string_parsed["v"]); // Will output Zu4WXiPRek that you can then
// validate for [a-zA-Z0-9] using a regex
The problem is that you are not requiring any particular number of characters in the v= part of the URL. So, for instance, checking
http://www.youtube.com/watch?v=Zu4WX£&P!ek
will match
http://www.youtube.com/watch?v=Zu4WX
and therefore return true. You need to either specify the number of characters you need in the v= part:
preg_match('~http://youtube.com/watch\?v=[a-zA-Z0-9-]{10}~', $videoLink)
or specify that the group [a-zA-Z0-9-] must be the last part of the string:
preg_match('~http://youtube.com/watch\?v=[a-zA-Z0-9-]+$~', $videoLink)
Your other example
http://www.youtube.com/watch?v=!Zu4WX£&P4ek
does not match, because the + sign requires that at least one character must match [a-zA-Z0-9-].
Short answer:
preg_match('%(http://www.youtube.com/watch\?v=(?:[a-zA-Z0-9-])+)(?:[&"\'\s])%', $videoLink)
There are a few assumptions made here, so let me explain:
I added a capturing group ( ... ) around the entire http://www.youtube.com/watch?v=blah part of the link, so that we can say "I want get the whole validated link up to and including the ?v=movieHash"
I added the non-capturing group (?: ... ) around your character set [a-zA-Z0-9-] and left the + sign outside of that. This will allow us to match all allowable characters up to a certain point.
Most importantly, you need to tell it how you expect your link to terminate. I'm taking a guess for you with (?:[&"\'\s])
?) Will it be in html format (e.g. anchor tag) ? If so, the link in href will obviously end with a " or '.
?) Or maybe there's more to the query string, so there would be an & after the value of v.
?) Maybe there's a space or line break after the end of the link \s.
The important piece is that you can get much more accurate results if you know what's surrounding what you are searching for, as is the case with many regular expressions.
This non-capturing group (in which I'm making assumptions for you) will take a stab at finding and ignoring all the extra junk after what you care about (the ?v=awesomeMovieHash).
Results:
http://www.youtube.com/watch?v=Zu4WXiPRek
- Group 1 contains the http://www.youtube.com/watch?v=Zu4WXiPRek
http://www.youtube.com/watch?v=Zu4WX&a=b
- Group 1 contains http://www.youtube.com/watch?v=Zu4WX
http://www.youtube.com/watch?v=!Zu4WX£&P4ek
- No match
a href="http://www.youtube.com/watch?v=Zu4WX&size=large"
- Group 1 contains http://www.youtube.com/watch?v=Zu4WX
http://www.youtube.com/watch?v=Zu4WX£&P!ek
- No match
The "v=..." blob is not guaranteed to be the first parameter in the query part of the URL. I'd recommend using PHP's parse_url() function to break the URL into its component parts. You can also reassemble a pristine URL if someone began the string with "https://" or simply used "youtube.com" instead of "www.youtube.com", etc.
function get_youtube_vidid ($url) {
$vidid = false;
$valid_schemes = array ('http', 'https');
$valid_hosts = array ('www.youtube.com', 'youtube.com');
$valid_paths = array ('/watch');
$bits = parse_url ($url);
if (! is_array ($bits)) {
return false;
}
if (! (array_key_exists ('scheme', $bits)
and array_key_exists ('host', $bits)
and array_key_exists ('path', $bits)
and array_key_exists ('query', $bits))) {
return false;
}
if (! in_array ($bits['scheme'], $valid_schemes)) {
return false;
}
if (! in_array ($bits['host'], $valid_hosts)) {
return false;
}
if (! in_array ($bits['path'], $valid_paths)) {
return false;
}
$querypairs = explode ('&', $bits['query']);
if (count ($querypairs) < 1) {
return false;
}
foreach ($querypairs as $querypair) {
list ($key, $value) = explode ('=', $querypair);
if ($key == 'v') {
if (preg_match ('/^[a-zA-Z0-9\-_]+$/', $value)) {
# Set the return value
$vidid = $value;
}
}
}
return $vidid;
}
Following regex will match any youtube link:
$pattern='#(((http(s)?://(www\.)?)|(www\.)|\s)(youtu\.be|youtube\.com)/(embed/|v/|watch(\?v=|\?.+&v=|/))?([a-zA-Z0-9._\/~#&=;%+?-\!]+))#si';