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!
$str = substr($string, 0, strrpos($string, ';'));
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);
str_replace
<?php
$string='This;is;my;long;string';
str_replace(';string','',$string); ?>
$str = rtrim($str, ';string');
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.
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);
}
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);