user3261212
user3261212

Reputation: 439

How to remove part of a string with php?

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

Answers (8)

ReeCube
ReeCube

Reputation: 2597

There are different ways:

basename:

$img = "../images/image2.jpg";
$img = basename($img);

explode and end:

$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = end($parts); // takes the last element in $parts

explode and array_pop:

$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = array_pop($parts);  // takes the last element in $parts and removes it

str_replace:

$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

The basename() would be helpful for you.

<?php
$img = "../images/image2.jpg";
$img = basename($img); //holds just `image2.jpg`

Upvotes: 5

Abhishek
Abhishek

Reputation: 567

You can do this

$subject = 'REGISTER 11223344 here';
$search = '11223344'
$trimmed = str_replace($search, '', $subject);
echo $trimmed

Upvotes: 0

jmoyson
jmoyson

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

Ben Swinburne
Ben Swinburne

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

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

 $imgout = str_replace("../images/", '', $img);

or use explode()

 $imgout = explode('/', $img);
 $imgname = $imgout[2];

Upvotes: 0

vandango
vandango

Reputation: 567

This should work:

$img = str_replace('../images/', '', $img);

Upvotes: 0

Dean Whitehouse
Dean Whitehouse

Reputation: 894

You could use PHP explode to separate the strings

http://www.php.net/explode

http://php.net/array_pop

$img = "../images/image2.jpg";

$parts = explode('/', $img);

$img = array_pop($parts);

Upvotes: 2

Related Questions