Remove part of a string in PHP - php

How can I keep a part from a string:
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
I want to keep all after /_hd/.
I try with this but it keeps the hd/:
echo substr($str, strpos($str, '_hd/') + 1);
// hd/791df3a1355efd3.jpg
Thanks.

you could simply use pathinfo method which will parse your path and return an array like this
array(4) {
["dirname"]=>
string(37) "../assets/uploads/8b3da36c4bce050/_hd"
["basename"]=>
string(19) "791df3a1355efd3.jpg"
["extension"]=>
string(3) "jpg"
["filename"]=>
string(15) "791df3a1355efd3"
}
for you what you are looking for will be called basename
$path = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
echo pathinfo($path)['basename']; // 791df3a1355efd3.jpg

Considering the example string witch appears to be a path and also assuming it is a single line, I propose a couple of examples with the first preferred.
<?php
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
echo basename($str);
This will output 791df3a1355efd3.jpg
<?php
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
echo preg_replace('#^.+\/#', '', $str);
This will output 791df3a1355efd3.jpg
With the second example if you also wanted to make sure /_hd/ is in the string
<?php
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
echo preg_replace('#^.+\/_hd\/#', '', $str);
and to get an array of values checking if /_hd/ is in the string (you can use basename() instead of preg_replace())
<?php
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
$files = array();
if (preg_match('#\/_hd\/#', $str)) {
$files[] = preg_replace('#^.+\/_hd\/#', '', $str);
}
var_dump($files);
echo is for testing but you can assign the result to a variable instead in both cases.

You can use the explode function
<?php
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
$explode = explode('/',$str);
echo $result = $explode['5'];
?>

You may try this, for example
$name = substr($str, strrpos($str, '/', -1) + 1);
or
$items = explode($str, '/');
$name = $items[count($items) - 1];

Related

How to trim string from right in PHP?

I have a string example
this-is-the-example/exa
I want to trim /exa from the above line
$string1 = "this-is-the-example/exa";
$string2 = "/exa";
I am using rtrim($string1, $sting2)
But the output is this-is-the-exampl
I want to this-is-the-example as output.
Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..
There are various approaches you can use for this:
With substr(DEMO):
function removeFromEnd($haystack, $needle)
{
$length = strlen($needle);
if(substr($haystack, -$length) === $needle)
{
$haystack = substr($haystack, 0, -$length);
}
return $haystack;
}
$trim = '/exa';
$str = 'this-is-the-example/exa';
var_dump(removeFromEnd($str, $trim));
With regex(DEMO):
$trim = '/exa';
$str = 'this-is-the-example/exa';
function removeFromEnd($haystack, $needle)
{
$needle = preg_quote($needle, '/');
$haystack = preg_replace("/$needle$/", '', $haystack);
return $haystack;
}
var_dump(removeFromEnd($str, $trim));
First explode the string, remove last element from exploded array using array_pop, then implode it back again with /.
$str = "this-is-the-example/exa";
if(strpos($str, '/') !== false)
{
$arr = explode('/', $str);
array_pop($arr);
$str = implode('/', $arr);
// output this-is-the-example
}
This will work event if you have multiple / in the URL and will remove last element only.
$str = "this-is-the-example/somevalue/exa";
if(strpos($str, '/') !== false)
{
$arr = explode('/', $str);
array_pop($arr);
$str = implode('/', $arr);
// output this-is-the-example
}
Say hi to strstr()
$str = 'this-is-the-example/exa';
$trim = '/exa';
$result = strstr($str, $trim, true);
echo $result;
You can use explode
<?php
$x = "this-is-the-example/exa";
$y = explode('/', $x);
echo $y[0];
the second parameter of rtrim is a character mask and not a string, your last "e" is trimed and that's normal.
COnsider using something else, regexp for example (preg_replace) to fit your needs
This keeps everything before "/" char :
$str = preg_replace('/^([^\/]*).*/','$1', 'this-is-the-example/exa');
This removes the last part.
$str = preg_replace('/^(.*)\/.*$/','$1', 'this-is-the-example/exa/mple');
Hope this helps. :)
Simply try this code:
<?php
$this_example = substr("this-is-the-example/exa", 0, -4);
echo "<br/>".$this_example; // returns "this-is-the-example"
?>
To allow for error handling, if the substring is not found in the search string ...
<?php
$myString = 'this-is-the-example/exa';
//[Edit: see comment below] use strrpos, not strpos, to find the LAST occurrence
$endPosition = strrpos($myString, '/exa');
// TodO; if endPosition === False then handle error, substring not found
$leftPart = substr($myString, 0, $endPosition);
echo($leftPart);
?>
outputs
this-is-the-example

How to remove 4th letter in string using PHP?

How to remove 4th letter in string using PHP ?
I use this code.
<?php
$str = "1234567890";
$str2 = mb_substr($str, 4);
echo $str2;
?>
But it's will echo 567890
I want to echo 123567890 remove 4 from string.
How can i do ?
You can try substr_replace for this. Here we are replacing 4 which is at 3rd index.
Try this code snippet here
<?php
$str = "1234567890";
echo substr_replace($str, "", 3,1);
try setting the 3rd index to null
<?php
$str = "1234567890";
$str[3] = null;
echo $str;
try with below sulution:
$str = '1234567890';
$str_arr = str_split($str);
unset($str_arr[3]);
echo implode('', $str_arr);
output:
123567890
There are multiple ways of performing any operations on string variables in php
// can be used for printing purpose
$str = "1234567890";
echo substr($str,0,3).substr($str,4);
// actual replacement of string
$str = "1234567890";
echo substr_replace($str, "", 3,1);

PHP Remove middle section of a string

I have a url that will always look like some variation of this
https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg
I need to remove with PHP the resolution specifier "-150x150" so that it reads
https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg
If it's always -150x150 you can just use str_replace():
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$stripped = str_replace('-150x150', '', $url);
var_dump($stripped);
// string(62) "https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg"
If you need a way to strip out any resolution, you can use a regular expression for that:
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$stripped = preg_replace('/-[0-9]+x[0-9]+/', '', $url);
var_dump($stripped);
// string(62) "https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg"
hello you can use strpos() and substr() functions
<?php
$str1 = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$str2 = "-150x150";
$pos = strpos($str1, $str2);
$part1 = substr($str1, $pos);
$part2 = substr($pos+1, strlen($str1));
$final_str = $part1.$part2;
echo $final_str;
?>
or you can also just use str_replace() and replace the part of the url by nothing :
<?php
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$str = "-150x150";
// will replace $str by '' in $url
$url = str_replace($str, '', $url);
echo $url;
?>
If it's not always 150x150, here's a nifty solution.
$url = 'https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg';
First get the extension
$ext = explode('.', $url);
$ext = $ext[count($ext)-1];
Then split by '-'
$array = explode('-', $url);
Pop the last array element which will be the resolution (150x150 here)
array_pop($array);
Then implode by '-' again and concatenate the extension to the new url
$new_url = implode('-', $array). '.' .$ext;

preg_replace is modifying JavaScript

I have a template tool, that replaces placeholders one of the pieces of the tool loads other files, here is what I am using for debugging:
var_dump($string);
$tmp = preg_replace('/\\$import\(("|\')' . $f . '("|\')\).*;/i', $string, $tmp);
var_dump($tmp);
The first var_dump prints out the contents of a file, and in the file there is this line of JavaScript:
$("#image-menu .info").html(text.replace(/(.+?:)/, "<b>$1</b>"));
After the pre_replace I have the second var_dump which then prints out this:
$("#image-menu .info").html(text.replace(/(.+?:)/, "<b>"</b>"));
As you can see $1 was replaced by a ", and I am not sure why. Any ideas as to why it is getting replaced?
Here is the full method:
private function loadIncludes(){
$tmp = $this->template;
$matches = array();
preg_match_all('/(\\$import\(("|\')(.+?)("|\')\).*;)/i', $tmp, $matches);
$files = $matches[3];
$replace = 0;
foreach($files as $key => $file){
$command = preg_replace("/\\\$import\((\"|').+?(\"|')\)/", "", $matches[0][$key]);
$string = $this->import($file);
$string = $this->runFunctions($string, "blah" . $command);
$f = preg_quote($file, "/");
var_dump($string);
$tmp = preg_replace('/\\$import\(("|\')' . $f . '("|\')\).*;/i', $string, $tmp);
var_dump($tmp);
$replace++;
}
$this->template = $tmp;
if($replace > 0){
$this->loadIncludes();
}
}
Within single quotes you can't use control characters like \r or \n, meaning you don't have to double-escape your $. Your \\$ can simply be \$.

Extracting part of a string?

How can I extract 4 from this string?
$string = "Rank_1:1:4";
I'm trying to get pagerank from Googles server, and the last value (4) is the actual pagerank.
Try
$string = "Rank_1:1:4";
$data = explode(':',$string);
echo end($data);
EDIT
as per #MichaelHampton, if they add more fields later, then use as below
$string = "Rank_1:1:4";
$data = explode(':',$string);
echo $data[2];
PHP has so many string function you can use ...
Variables
$find = ":";
$string = "Rank_1:1:4";
Using substr
echo substr($string, strrpos($string, $find) + 1);
Using strrchr
echo ltrim(strrchr($string, $find),$find);
$pattern = '/:\d+$/';
preg_match($pattern, $string, $matches);
$rank = substr($matches[0],1);

Categories