remove before specific string not character - php

Format of string is as follow
$img = "/images/posts/main.jpg";
$img1 = "/images/posts/john.jpg";
I need to remove /images/posts/ and echo rest of the content.
I tried with strstr, But I found it deals with only character
echo strstr($img, '/images/posts/')
//output => /images/posts/main.jpg
if I use only single character echo strstr($img, '/') Then output is images/posts/.
So I use substr with strstr to get expected result.
echo substr(strstr($img, '/'), 14);
//output => main.jpg
In my case, I am sure it will work constantly with same result because the part images/posts/ remains same and will not change.
But is it really good or fast way to counting and trimming ? Any other fast way to cut /images/posts/ at once ?
Or replace ? is it faster ??
echo str_replace('/images/posts/','',$img);

You can do like this..
Syntax-
str_replace(find, replace, string, count)
For Eg-
str_replace('/images/posts/', '', '/images/posts/main.jpg');
it will print main.jpg

Related

PHP strrchr parse int

I've got a problem. This is my PHP code :
$extract = $query;
$extractpoint = strrchr($extract, ".");
So, $extract is a parse_url of my website address.
Exemple : http://test.com?param.6
$extract = param.6 and $extractpoint = .6
BUT, I want a solution to have only the 6, without the point.
Can you help me with that ?
The easiest solution would be restructuring the URL. I that is not possible though you can use strpos to find the position of your specific character and then use substr to select the characters after it.
$extract = 'param.6';
echo substr($extract, strpos($extract, '.') + 1);
Demo: https://3v4l.org/CudTAG
(The +1 is because it returns the position of the match and you want to be one place past that)
There are different ways:
Filter only numbers:
$int = filter_var($extractpoint, FILTER_SANITIZE_NUMBER_INT);
Replace the point
$int = str_replace('.', '', $extractpoint)
//$int = str_replace('param.', '', $extractpoint)
Use regex
/[0-9+]/'
strrchr() results the count of the last instance of a character in a string. In order to get the next character add 1 to the count. Then use substr() to extract the next character from the string.
http://php.net/manual/en/function.strrchr.php
http://php.net/manual/en/function.substr.php

how to start string from specific character and remove unwanted characters

I have URL of file which looks like this
movieImages/1`updateCategory.PNG
it should look like this
updateCategory.PNG
you can use like this, simple
$string = 'movieImages/1`updateCategory.PNG';
$ser = 'movieImages/1`';
$trimmed = str_replace($ser, '', $string);
echo $trimmed;
output will be updateCategory.PNG
Find the position of unwanted character and then pick up the substring after that position.
$str="movieImages/1`updateCategory.PNG";
$unwanted="`";
echo substr($str,strpos($str,$unwanted)+1);
Output
updateCategory.PNG
Fiddle
That is if the string can vary in structure and size. If the first part will always remain same you can simply remove the unwanted stuff using str_replace.
echo str_replace('movieImages/1`','',$str);

PHP Strip String, Convert to int

I have a STRING $special which is formatted like £130.00 and is also an ex TAX(VAT) price.
I need to strip the first char so i can run some simple addition.
$str= substr($special, 1, 0); // Strip first char '£'
echo $str ; // Echo Value to check its worked
$endPrice = (0.20*$str)+$str ; // Work out VAT
I don't receive any value when i echo on the second line ? Also would i then need to convert the string to an integer in order to run the addition ?
Thanks
Matt
+++ UPDATE
Thanks for your help with this, I took your code and added some of my own, There are more than likely nicer ways to do this but it works :) I found out that if the price was below 1000 would look like £130.00 if the price was a larger value it would include a break. ie £1,400.22.
$str = str_replace('£', '', $price);
$str2 = str_replace(',', '', $str);
$vatprice = (0.2 * $str2) + $str2;
$display_vat_price = sprintf('%0.2f', $vatprice);
echo "£";
echo $display_vat_price ;
echo " (Inc VAT)";
Thanks again, Matt
You cannot use substr the way you are using it currently. This is because you are trying to remove the £ char, which is a two-byte unicode character, but substr() isn't unicode safe. You can either use $str = substr($string, 2), or, better, str_replace() like this:
$string = '£130.00';
$str = str_replace('£', '', $string);
echo (0.2 * $str) + $str; // 156
Original answer
I'll keep this version as it still can give some insight. The answer would be OK if £ wouldn't be a 2byte unicode character. Knowing this, you can still use it but you need to start the sub-string at offset 2 instead of 1.
Your usage of substr is wrong. It should be:
$str = substr($special, 1);
Check the documentation the third param would be the length of the sub-string. You passed 0, therefore you got an empty string. If you omit the third param it will return the sub-string starting from the index given in the first param until the end of the original string.

If second to last character is numeric

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)) {}

rtrim with underscore in php

I have line as 'Delux Room_room'. I want get 'Delux Room' as result. I tried following codes.
Following code give following result.
echo $row.'<br/>';
echo rtrim($row, 'room') .'<br/>';
echo rtrim($row, '_room') .'<br/>';
Result ;-
Delux Room_room
Delux Room_
Delux R
But i want Delux Room. Please help me.
echo rtrim($row, '_room') .'<br/>';
That says "remove characters from the end of the string until you get to one that isn't _, r, o or m." Which obviously isn't what you mean. From the PHP manual:
$charlist You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
You provide a list of characters, not a string you want to remove.
You should probably use substr instead:
echo substr($row, 0, -5); // remove the last 5 characers
Another solution would be to use str_replace to replace unwanted substrings:
echo str_replace('_room', '', $row); // replace "_room" with an empty string
Note that this is less precise than the substr approach.
rtrim's second argument is a set of characters. You'll have to write your own method to remove a specific string instead:
function rtrim_str($str, $trim) {
if (substr($str, -strlen($trim)) == $trim) {
return substr($str, 0, -strlen($trim));
}
return $str; // String not present at end
}
echo rtrim_str($row, '_room');
Alternatively to #lonesomeday's solution, if your last past is of variable length:
$pos = strrpos($row, '_');
echo $substr($row, 0, $pos);
You should use str_replace instead of rtrim, like this:
echo $row.'<br/>';
echo str_replace('room', '', $row) .'<br/>';
echo str_replace('_room', '', $row) .'<br/>';

Categories