PHP Find and replace a part of string

2019-08-29 14:18发布

问题:

I have an input string. Format is below:

This;is;my;long;string

Any fast solution (a lot of strings) to get this output string using PHP:

This;is;my;long

I need to remove this appendix: ;string

  • I don't know the length of appendix: ;any letters here.

Thanks!

回答1:

$str = substr($string, 0, strrpos($string, ';'));


回答2:

If you're consistently using ; as the delimiter, you can explode() the string, remove the last index, then rejoin the string using implode():

$str    = "This;is;my;long;string";
$strArr = explode(";", $str);

unset($strArr[count($strArr) - 1]);
$newStr = implode(";", $strArr);

UPDATE

In order to make this work for any searchable string, you can use array_keys():

$str             = "This;is;my;long;string";
$strArr          = explode(";", $str);
$searchStr       = "string";
$caseSensitive   = false;
$stringLocations = array_keys($strArr, $searchStr, $caseSensitive);

foreach ($stringLocations as $key) {
    unset($strArr[$key]);
}
$newStr = implode(";", $strArr);

Or, even quicker, you can use array_diff():

$str       = "This;is;my;long;string";
$strArr    = explode(";", $str);
$searchStr = array("string");
$newArray  = array_diff($searchStr, $strArr);
$newStr    = implode(";", $newArray);


回答3:

str_replace

<?php 
$string='This;is;my;long;string';
str_replace(';string','',$string); ?>


回答4:

$str = rtrim($str, ';string');


回答5:

If you know that ;string will always be there (most of the time anyhow) you can use rtrim:

$trimmed = rtrim($text, ";string");

This will remove only the trailing ;string from the string. Unless it exists on the end of the string , it won't be deleted.



回答6:

Not sure if the piece you want to remove is consistently at the beginning or not.

$array = explode(";" , $string);
foreach ( $array as $key => $arr ) {
    if ( $arr == "string" ) {
        unset($array[$key]);
        break;
    }
    echo implode(";" , $array);
}


回答7:

If the string is always formatted that way you can't go wrong with substr - probably the fastest way

$str = 'This;is;my;long;string';
$str = substr( $str, 0, -7);