Reputation: 439
Hello guys so I have a string where the begin part is the same
the string looks like this where the begin part is always ../images/
$img = "../images/image2.jpg";
but the image2.jpg can be something like image_23423.png
how can I remove the ../images/ part?
I tought about str_replace but Could not get it to work
Thanks in advance
Upvotes: 1
Views: 90
Reputation: 2597
There are different ways:
$img = "../images/image2.jpg";
$img = basename($img);
$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = end($parts); // takes the last element in $parts
$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = array_pop($parts); // takes the last element in $parts and removes it
$img = "../images/image2.jpg";
$img = str_replace('../images/', '', $img);
There are more ways to do this, but those are the most important ones.
Upvotes: 1
Reputation: 68476
The basename()
would be helpful for you.
<?php
$img = "../images/image2.jpg";
$img = basename($img); //holds just `image2.jpg`
Upvotes: 5
Reputation: 567
You can do this
$subject = 'REGISTER 11223344 here';
$search = '11223344'
$trimmed = str_replace($search, '', $subject);
echo $trimmed
Upvotes: 0
Reputation: 146
Try this:
PHP
$path = "../images/image2.jpg";
$path_arr = explode("/", $path);
echo $path_arr[0]; // ..
echo $path_arr[1]; // images
echo $path_arr[2]; // image2.jpg
Upvotes: 0
Reputation: 26467
pathinfo()
will suitably extract the information you need from the string. See https://www.php.net/pathinfo
$img = "../images/image2.jpg";
$imgDetails = pathinfo($img);
$imgName = $imgDetails['basename'];
print_r($imgDetails); // Will show you what other formats you can get the filename in, including extension etc.
basename()
is also exposed as a function which you could use
Upvotes: 0
Reputation: 13728
$imgout = str_replace("../images/", '', $img);
or use explode()
$imgout = explode('/', $img);
$imgname = $imgout[2];
Upvotes: 0
Reputation: 894
You could use PHP explode to separate the strings
$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = array_pop($parts);
Upvotes: 2