如何用PHP删除部分字符串?

时间:2014-03-18 09:36:00

标签: php

大家好,所以我有一个开头部分相同的字符串

字符串看起来像这样,开始部分始终是../ images /

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

但是image2.jpg可以像image_23423.png

如何删除../ images / part?

我讨论过str_replace但无法让它工作

提前致谢

8 个答案:

答案 0 :(得分:5)

basename()会对您有所帮助。

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

答案 1 :(得分:2)

您可以使用PHP explode来分隔字符串

http://www.php.net/explode

http://php.net/array_pop

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

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

$img = array_pop($parts);

答案 2 :(得分:1)

有不同的方式:

<强> basename

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

explodeend

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

explodearray_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);

有更多方法可以做到这一点,但那些是最重要的方法。

答案 3 :(得分:0)

这应该有效:

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

答案 4 :(得分:0)

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

或使用explode()

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

答案 5 :(得分:0)

pathinfo()将适当地从字符串中提取您需要的信息。见http://uk3.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()也作为您可以使用的函数公开

答案 6 :(得分:0)

试试这个:

<强> PHP

$path = "../images/image2.jpg";
$path_arr = explode("/", $path);
echo $path_arr[0]; // ..
echo $path_arr[1]; // images
echo $path_arr[2]; //  image2.jpg

答案 7 :(得分:0)

你可以这样做

$subject = 'REGISTER 11223344 here';
$search = '11223344'
$trimmed = str_replace($search, '', $subject);
echo $trimmed
相关问题