php remove everything in the string, keep the last digits - php

I have values like below:
$var1 = car-123-244343
$var2 = boat-2-1
$var3 = plane-311-23
I need to remove everything and keep the last digit/ditgits after the second hyphen
Expecting values:
244343
1
23
This is what I've got
$stripped = preg_replace('^[a-z]+[-]$', '', 'car-123-244343');
I got a big red error No ending delimiter '^' found

Without regex:
$var1 = substr($var1, strrpos($var1, '-') + 1);
What this does is the same as:
$pos = strrpos($var1, '-') + 1 takes the last postion of '-' and adds 1 for starting at the next character
substr($var, $pos) takes the $var and returns the substring starting in $pos.
I think is less expensive than using regex.
Edit:
As pointed below by konforce, if you are not sure which all the strings have that format, you have to verify it.

this function will work:
function foo($value)
{
$split = explode('-', $value);
return $split[count($split)-1];
}

Here is a fun version with explode:
list($vehicle, $no1, $no2) = explode('-', $data);

First, that error means your regex needs to be enclosed in delimiters (below I use the classic /).
Second, I would rewrite your regex to this:
$stripped = preg_replace('/.+?(\d+)$/', '$1', 'car-123-244343');
If you can operate on the assumption that what comes after the last - is always a number, the other solutions also work.

With regex:
$endnumber = preg_replace('/.*[^0-9]/', '', $input);
Remove everything up till, and including, the last non-digit.

Related

Remove empty space and plus sign from the beginning of a string

I have a string that begins with an empty space and a + sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first + sign using PHP. I've tried ltrim, preg_replace with several patterns and with trying to escape the + sign, I've also tried substr and str_replace. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a + sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the + sign. I'm using get_the_excerpt Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the + with substr($s, 2);, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6); and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s); which shows you exactly what you have there.
You can use explode like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
str_replace
$string = str_replace('+', '', $string);
preg_replace
$string = preg_replace('/^\+/', '', $string);
ltrim
$string = ltrim($string, '+');
substr
$string = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can use ltrim() or substr().
For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim in the above example removes all spaces and addition characters from the left hand side of the original string.

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.

How do I remove texts after the second comma in php

How can I remove the texts in a sentence after the second comma but do nothing if it has no two commas in a sentence?
I tried the following:
substr($str, 0, strpos($str, ',', strpos($str, ',')+1))
But the problem here is if I don't have two commas in this $str, the funtion outputs nothing, I'm getting a blank area.
Is there anyway to check the existence of two commas and remove text after the second comma or do nothing otherwise.
Try this:
$commasCount = count(explode(',', $str));
if ($commasCount > 2) {
$str = substr($str, 0, strpos($str, ',', strpos($str, ',')+1));
}
A more elegant approach, without using string functions and reusing the array as we need it to count the number of commas anyway (and avoiding regex madness for readability):
$text_segments = explode(',', $str);
if( count($text_segments) > 2 ) {
$str = $text_segments[0] . ',' . $text_segments[1];
}
Just check the # of occurrences first:
if (substr_count($str, ',') >= 2)
substr($str, 0, strpos($str, ',', strpos($str, ',')+1));
Or you could do it with preg_match() but it would be slower:
if (preg_match('/([^,]*,){2}/', $str, $match))
$str = $match[1];
Or in a single step (ala adeneo above, but altered to fit the instructions)
$str = preg_replace('/((?:[^,]*,){2})?(?:.*)$/', '$1', $str);
You'll notice the initial characters with comma at the end are made optional by the question-mark at the end of (...)? so it will get the correct value regardless.
Assuming that you want to remove the second comma and all subsequent characters (because of your selected answer), using regex is very concise and direct and can be written without any pre-checking and conditions.
Match the first the first occurring comma, match one or more non-comma characters, then forget those characters with \K, then explicitly match the second comma and all remaining characters -- to be replaced with an empty string.
Code: (Demo)
$str = "a,b,c,d";
var_export(
preg_replace("/,[^,]+\K,.*/", '', $str)
);

Replace all the _ except one before last one

I have the following url:
http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg
I want to replace the _ with .. However, the _7 at the end should be kept - it is not a dot.
So, basically it should look like:
http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
If I use str_replace it will replace all the _ but I need to keep that one there. How can I do this?
Use this (corrected now!)
<?php
$subject = 'http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg';
$pattern = '/(_)(?!\d_jpg)/';
var_dump(preg_replace($pattern, '.', $subject));
This outputs
http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
Here's a solution that doesn't use regex (works for all numbers, so this won't fail if the number is different from 7; it doesn't have to be a number -- a string works, too):
<?php
$haystack = 'http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg';
//replacing all '_' with '.'
$haystack = str_replace('_', '.', $haystack);
//finding second last occurence of '.'
$n = strrpos($haystack, '.', strrpos($haystack, '.') - strlen($haystack) - 1);
//replacing the nth character to '_'
$haystack[$n] = '_';
echo $haystack;
Output:
http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
Demo!
You can use this negative lookahead based regex code:
$s='http://distilleryimage3_s3_amazonaws_com/8af11cdcf11e286b022000ae90285_7_jpg';
$repl = preg_replace('/_(?![^_]*_[^_]*$)/', '.', $s);
//=> http://distilleryimage3.s3.amazonaws.com/8af11cdcf11e286b022000ae90285_7.jpg
The final _ in a string that is not itself.
_(?=[^_]+$)
Edit: my assumption is that this question needs specific knowledge of file extensions to answered correctly.

How to replace the Last "s" with "" in 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

Categories