How to replace the Last "s" with "" in PHP - php

I need to know how I can replace the last "s" from a string with ""
Let's say I have a string like testers and the output should be tester.
It should just replace the last "s" and not every "s" in a string
how can I do that in PHP?

if (substr($str, -1) == 's')
{
$str = substr($str, 0, -1);
}

Update: Ok it is also possible without regular expressions using strrpos ans substr_replace:
$str = "A sentence with 'Testers' in it";
echo substr_replace($str,'', strrpos($str, 's'), 1);
// Ouputs: A sentence with 'Tester' in it
strrpos returns the index of the last occurrence of a string and substr_replace replaces a string starting from a certain position.
(Which is the same as Gordon proposed as I just noticed.)
All answers so far remove the last character of a word. However if you really want to replace the last occurrence of a character, you can use preg_replace with a negative lookahead:
$s = "A sentence with 'Testers' in it";
echo preg_replace("%s(?!.*s.*)%", "", $string );
// Ouputs: A sentence with 'Tester' in it

$result = rtrim($str, 's');
$result = str_pad($result, strlen($str) - 1, 's');
See rtrim()

Your question is somewhat unclear whether you want to remove the s from the end of the string or the last occurence of s in the string. It's a difference. If you want the first, use the solution offered by zerkms.
This function removes the last occurence of $char from $string, regardless of it's position in the string or returns the whole string, when $char does not occur in the string.
function removeLastOccurenceOfChar($char, $string)
{
if( ($pos = strrpos($string, $char)) !== FALSE) {
return substr_replace($string, '', $pos, 1);
}
return $string;
}
echo removeLastOccurenceOfChar('s', "the world's greatest");
// gives "the world's greatet"
If your intention is to inflect, e.g singularize/pluralize words, then have a look at this simple inflector class to know which route to take.

$str = preg_replace("/s$/i","",rtrim($str));

The very simplest solution is using rtrim()
That is exactly what that function is intended to be used for:
Strip whitespace (or other characters) from the end of a string.
Nothing simpler than that, I am not sure why, and would not follow the suggestions in this thread going from regex to "if/else" blocks.
This is your code:
$string = "Testers";
$stripped = rtrim( $string, 's' );
The output will be:
Tester

Related

PHP - How to remove specific character at a string?

i have more + symbol in my string and i want to remove last one and any character after it
ex
Giza+badrashen+test
You can explode your string on '+' and then join it ignoring the last element of the split (with array_slice with negative index), like this (assuming $str is your string)
$result = join('', array_slice(explode('+', $str), -1));
In case you suspect your string may not contain a '+', you can check for its presence first with strpos
if(strpos($str, '+') !== false) {
$result = join('', array_slice(explode('+', $str), -1));
}
A simple regex solution:
Assuming you have Giza+badrashen+test and want Giza+badrashen as result.
echo preg_replace("/\+[^\+]*$/", "", "Giza+badrashen+test");
Tests:
var_dump(preg_replace("/\+[^\+]*$/", "", "Giza+badrashen+test"));
var_dump(preg_replace("/\+[^\+]*$/", "", "Giza+badrashen+test+"));
var_dump(preg_replace("/\+[^\+]*$/", "", "Giza"));
Output:
string(14) "Giza+badrashen"
string(19) "Giza+badrashen+test"
string(4) "Giza"
$string = "abc1234+12+3455+xzyabc";
$string = substr($string, 0, strrpos($string,"+"));
echo $string;
> abc1234+12+3455
EDIT: and gives an empty string if there is no + but it doesn't crash/fail
EDIT2: I slightly mis-read the question the first time, my edited answer is even simpler
Regex with a negative lookahead might be the most compact solution:
$myString="foo-bar+foo+foobar";
$result = preg_split("/\+(?!.*\+)/", $myString);
echo $result[0];
//result: foo-bar+foo
No need of additional check, cause in case no + is found it just gives back the original string.
It's just worth pointing that the + must be escaped having special meaning in all flowers of regex...

php regex replace each character with asterisk

I am trying to something like this.
Hiding users except for first 3 characters.
EX)
apple -> app**
google -> goo***
abc12345 ->abc*****
I am currently using php like this:
$string = "abcd1234";
$regex = '/(?<=^(.{3}))(.*)$/';
$replacement = '*';
$changed = preg_replace($regex,$replacement,$string);
echo $changed;
and the result be like:
abc*
But I want to make a replacement to every single character except for first 3 - like:
abc*****
How should I do?
Don't use regex, use substr_replace:
$var = "abcdef";
$charToKeep = 3;
echo strlen($var) > $charToKeep ? substr_replace($var, str_repeat ( '*' , strlen($var) - $charToKeep), $charToKeep) : $var;
Keep in mind that regex are good for matching patterns in string, but there is a lot of functions already designed for string manipulation.
Will output:
abc***
Try this function. You can specify how much chars should be visible and which character should be used as mask:
$string = "abcd1234";
echo hideCharacters($string, 3, "*");
function hideCharacters($string, $visibleCharactersCount, $mask)
{
if(strlen($string) < $visibleCharactersCount)
return $string;
$part = substr($string, 0, $visibleCharactersCount);
return str_pad($part, strlen($string), $mask, STR_PAD_RIGHT);
}
Output:
abc*****
Your regex matches all symbols after the first 3, thus, you replace them with a one hard-coded *.
You can use
'~(^.{3}|(?!^)\G)\K.~'
And replace with *. See the regex demo
This regex matches the first 3 characters (with ^.{3}) or the end of the previous successful match or start of the string (with (?!^)\G), and then omits the characters matched from the match value (with \K) and matches any character but a newline with ..
See IDEONE demo
$re = '~(^.{3}|(?!^)\G)\K.~';
$strs = array("aa","apple", "google", "abc12345", "asdddd");
foreach ($strs as $s) {
$result = preg_replace($re, "*", $s);
echo $result . PHP_EOL;
}
Another possible solution is to concatenate the first three characters with a string of * repeated the correct number of times:
$text = substr($string, 0, 3).str_repeat('*', max(0, strlen($string) - 3));
The usage of max() is needed to avoid str_repeat() issue a warning when it receives a negative argument. This situation happens when the length of $string is less than 3.

PHP remove and delete something after one special character

I have a very simple PHP question about replacing in string.
For example, our string is this :
This is a test - spam text
and i need to convert this string to this :
This is a test
I mean i want to detect the place of - charachter and delete everything after that.
How to do it ?
One of the possible solutions:
$result = substr($str, 0, strpos($str, '-'));
use substr to return part of a string and strpos to find the position of the first occurrence of a substring in a string
$str = 'This is a test - spam text';
$newStr = substr($str, 0, strpos($str, '-'));
// start ^ end ^
Try
$str = "This is a test - spam text";
$str = substr($str, 0, strpos( $str, '-'));
strpos() detects where - is.
You can use Regular expressions to match anything after the - character.
This should work
/-.*/
When you match the string then you can replace the content using simple string functions.

how to remove last occurance of underscore in string

I have a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;

Replace only at the end of the string

echo $string can give any text.
How do I remove word "blank", only if it is the last word of the $string?
So, if we have a sentence like "Steve Blank is here" - nothing should not removed, otherwise if the sentence is "his name is Granblank", then "Blank" word should be removed.
You can easily do it using a regex. The \b ensures it's only removed if it's a separate word.
$str = preg_replace('/\bblank$/', '', $str);
As a variation on Teez's answer:
/**
* A slightly more readable, non-regex solution.
*/
function remove_if_trailing($haystack, $needle)
{
// The length of the needle as a negative number is where it would appear in the haystack
$needle_position = strlen($needle) * -1;
// If the last N letters match $needle
if (substr($haystack, $needle_position) == $needle) {
// Then remove the last N letters from the string
$haystack = substr($haystack, 0, $needle_position);
}
return $haystack;
}
echo remove_if_trailing("Steve Blank is here", 'blank'); // OUTPUTS: Steve blank is here
echo remove_if_trailing("his name is Granblank", 'blank'); // OUTPUTS: his name is Gran
Try the below code:
$str = trim($str);
$strlength = strlen($str);
if (strcasecmp(substr($str, ($strlength-5), $strlength), 'blank') == 0)
echo $str = substr($str, 0, ($strlength-5))
Don't use preg_match unless it is not required. PHP itself recommends using string functions over regex functions when the match is straightforward. From the preg_match manual page.
ThiefMaster is quite correct. A technique that doesn't involve the end of line $ regex character would be to use rtrim.
$trimmed = rtrim($str, "blank");
var_dump($trimmed);
^ That's if you want to remove the last characters of the string. If you want to remove the last word:
$trimmed = rtrim($str, "\sblank");
var_dump($trimmed);

Categories