Check what a variable ends with? - php

I'm stuck in my code.
My site's users are supposed to give me the link of a image that I will store in a variable.
How can I check what the link ends with, the extension if you will?

You can use any of these:
$ext = substr(strrchr(FILENAME, '.'), 1);
$ext = substr(FILENAME, strrpos(FILENAME, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', FILENAME);
Their performance differences are negligible (even when ran like a 500 000 times; tested with PHP 7 using phpcb)
The pathinfo() is like... really slow, compared to these, for just getting the (last) extension.

While Jefferson answer is correct; based on the problem an easier solution would be to use PATHINFO_EXTENSION.
pathinfo('/path/to/file/image.jpg', PHPINFO_EXTENSION); // returns 'jpg'

You can use the substring method "substr" to get the last couple characters after the last occuring period which you can find with "strrpos" I believe.
strrpos (See doc here) returns false if the last occurrence wasn't found and the index of the match if it is.
$mystring = 'stackoverflow.png';
$pos = strrpos($mystring,'.');
if($pos === false) { // Note the triple '='
// not found..
}else{
echo substr($mystring, $pos); // print '.png'
}

Related

Add a text in a string PHP

I have a text.
$text='userpics/115/X3WGOC0009JA.jpg';
I want to add a letter p before X3WGOC0009JA.jpg, so my output will be
$text='userpics/115/pX3WGOC0009JA.jpg';
---^
I am new to php, so I don't really know what to try, I was hoping you could guide me in the right direction
You can explode by the slash by one way.
$exploded_text = explode('/', $text);
$new_text = $exploded_text[0] . $exploded_text[1] . 'p' . $exploded_text[2];
It's not the best way, but it will work.
Based on his question, I think all he wants to do is:
$text='userpics/115/'.'p'.'X3WGOC0009JA.jpg';
First, I would get the filename using strrpos and substr:
$text = 'userpics/115/X3WGOC0009JA.jpg';
$prepend_filename = 'p';
$last_slash_pos = strrpos($text, '/');
if ($last_slash_pos === false) throw new Exception('No slashes found');
$path = substr($text, 0, $last_slash_pos);
$filename = substr($text, $last_slash_pos + 1); // Add one to skip slash
And then you can add the p (as specified in $prepend_filename) using this:
$new_path = $path . DIRECTORY_SEPARATOR . $prepend_filename . $filename;
Have you tried just setting you variables and concatenation if you doing this a bunch.
$p = 'p';
$new = "userpics/115/" . $p . "X3WGOC0009JA.jpg";
There is a function, substr_replace(), which can insert a string at a point you want.
We combine this with strRpos() which we can use to find the first slash, LOOKING IN REVERSE:
$string = substr_replace($string, 'p', strrpos($string, '/')+1 );
This will insert 'p' in $string. At the position of the '/' in $string. The +1 corrects the 'cursor' to the character AFTER the slash.
Why not use the explode functions?
Very simple: Those are slow. String functions like strpos() and substr_replace() are VERY fast, especially on small strings.
Arrays are WAY slower in php, so don't go there unless you have to. For simple string- manipulation you should use simple string functions (sounds easy when you put it like that doesnt it?).
In a simple test I benchmarked the explode variant like user3758531's VS the string variant like mine:
100.000 tries with arrays: 1.5 sec
100.000 tries with strings: 0.9 sec
In this one situation, with this one action timing doesnt really matter. But apply this way of thinking thoughout the website and you will notice it speeding up/slowing down.

ucfirst capitalizing the second letter when run at command line

I have a log method which saves to a file that is named the same as the script calling it, only with a capital first letter, which works sometimes, but other times capitalizes the second letter (I can't see any pattern as to when it does what but it's always consistent, meaning that file A will always either be initial capped or second letter capped, it's not arbitrary).
Here's my code...
function logData($str){
$filePath = $_SERVER["SCRIPT_FILENAME"];
$dir = substr($filePath, 0, strrpos($filePath, "/") + 1);
$fileName = substr($filePath,strrpos($filePath, "/")+1);
$fileName = preg_replace('/\w+$/','log',$fileName);
$fileName = ucfirst($fileName);
$fHandle = fopen( $dir.$fileName , "a");
$contents = fwrite($fHandle, $str ."\n");
fclose($fHandle);
}
Does anyone have any thoughts on what could be causing such an odd behavior *some of the time?
I know I can brute force it with a strtoupper on the first char and then append the rest of the string, but I'd really like to understand what (if anything) I'm doing wrong here.
This is probably a bug further up the code, where you calculate the $dir and $filename. If the path has a slash or not... a probably solution is .
if (strpos('/', $filePath) === false) {
$dir = '';
$fileName = $filePath;
} else {
$dir = substr($filePath, 0, strrpos($filePath, "/") + 1);
$fileName = substr($filePath,strrpos($filePath, "/")+1);
}
But echo those values out and concetrate there
You can forcefully downcase the file name before capitalizing the first letter. That is if all what you care about is capitalizing the first letter.
$fileName = ucfirst(strtolower($fileName));
On the docs for ucfirst it says (with my emphasis):
Returns a string with the first character of str capitalized, if that
character is alphabetic.
Depending on where you execute this script SCRIPT_FILENAME will return different results. Could it be possible that you execute the script from a different path, thus giving SCRIPT_FILENAME a relative path?
To test this theory, I ran the script below from some of your possible execution paths and saw possible examples include the prefix "./" and "/" which would likely not be considered as having alphabetic first characters.
<?php
error_reporting(E_ALL);
echo $_SERVER["SCRIPT_FILENAME"];
?>

Testing to see if a string contains any of a set of other strings in PHP

I am trying to test if a url leads to an image, such as "http://i.imgur.com/vLsht.jpg"
by testing to see if the string contains ".jpg" or ".png" or ".gif" etc.
My curent code is:
if (stripos($row_rsjustpost['link'], ".png") !== false) {
//do stuff
}
I would like to do something like
if (stripos($row_rsjustpost['link'], ".png" || ".jpg" || ".gif") !== false) {
//do stuff
}
This is an okay use of a regular expression via preg_match():
$matches = array();
if (preg_match('/\.(png|jpg|gif)/i', $row_rsjustpost['link'], $matches) {
// Contains one or more of them...
}
// $matches holds the matched extension if one was found.
print_r($matches);
Note: if the string must occur at the end like a file extension, terminate it with $:
/\.(png|jpg|gif)$/i
//-------------^^
If you were attempting to locate only one substring, it would be more appropriate to use stripos(), but you can match a number of different patterns with a regex, without having to cough out a long if/else chain.
If I didn't want to use regular expressions, here's how I'd do it:
Get the last 4 characters (the file extension)
$filepath = $row_rsjustpost['link'];
$extension = substr($filepath, length($filepath) - 4);
Then see if it matches a pattern:
if (in_array($extension, array(".png", ".jpg", ".gif"))) {
// Have a party!
}

how to get the first part?

eg:the GET array: $_GET['path']
which value may be : $_GET['path']==3,$_GET['path']==13_7,$_GET['path']==33_75_45,...
no matter what value $_GET['path'] has, i only want the first part of the value. how to get it?
list($a) =explode('_', $_GET['path']);
var_dump($a);
You could use something like this:
function getNumber($n)
{
$pos = strpos($n, "_");
return ($pos === false ? $n : substr($n, 0, $pos));
}
This will get the job done:
$splitPath = strstr($_GET['path'], "_", true);
$path = strlen($splitPath > 0) ? $splitPath : $_GET['path'];
It can probably be shortened a bit, but the idea here is that in the end you will always just use the $path variable. If $_GET['path'] contains _ then whatever number is before it will be returned (due to the true argument in strstr()) and if not then just the value of $_GET['path'] will be equal to $path. You may want to do some cleansing of the value though too, or at least make sure it's numeric (is_numeric()).
do you mean that the value of $_GET['path'] is delimited by _ ? if so,
<?php
list($firstPart,) = explode('_', $_GET['path'], 2);
echo $firstPart;
could be the one you need.
First of all your question is confusing
This may help you
if u want to find the first part
example : name3example.com
<?php
$result = strstr($_GET['path'], '3');
?>
// will return "name"
see the link for more details http://php.net/manual/en/function.strstr.php
Or if u want to get the part of a string u can use 'substr' function of php
see the link for more details http://www.php.net/manual/en/function.substr.php
Use parse_url in PHP to split an url in its various parts.
After that use strrpos to find the first occurrance of the required part in the path.
With substr you can copy the first part of the path (up until the found _) and you're done.

Regex: how to match the last dot in a string

I have two example filename strings:
jquery.ui.min.js
jquery.ui.min.css
What regex can I use to only match the LAST dot? I don't need anything else, just the final dot.
A little more on what I'm doing. I'm using PHP's preg_split() function to split the filename into an array. The function deletes any matches and gives you an array with the elements between splits. I'm trying to get it to split jquery.ui.min.js into an array that looks like this:
array[0] = jquery.ui.min
array[1] = js
If you're looking to extract the last part of the string, you'd need:
\.([^.]*)$
if you don't want the . or
(\.[^.]*)$
if you do.
I think you'll have a hard time using preg_split, preg_match should be the better choice.
preg_match('/(.*)\.([^.]*)$/', $filename, $matches);
Alternatively, have a look at pathinfo.
Or, do it very simply in two lines:
$filename = substr($file, 0, strrpos($file, '.'));
$extension = substr($file, strrpos($file, '.') + 1);
At face value there is no reason to use regex for this. Here are 2 different methods that use functions optimized for static string parsing:
Option 1:
$ext = "jquery.ui.min.css";
$ext = array_pop(explode('.',$ext));
echo $ext;
Option 2:
$ext = "jquery.ui.min.css";
$ext = pathinfo($ext);
echo $ext['extension'];
\.[^.]*$
Here's what I needed to exclude the last dot when matching for just the last "part":
[^\.]([^.]*)$
Using a positive lookahead, I managed this answer:
\.(?=\w+$)
This answer matches specifically the last dot in the string.
I used this - give it a try:
m/\.([^.\\]+)$/

Categories