PHP - How to remove specific character at a string? - php

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...

Related

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.

Cut string from end to specific char in php

I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.
Thanks
In this special case, an url, use basename() :
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace(), like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.
Use
explode() AND end()
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Working Demo
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));

Extract all strings values from code

everyone. I have a problem and I can't resolve it.
Pattern: \'(.*?)\'
Source string: 'abc', 'def', 'gh\'', 'ui'
I need [abc], [def], [gh\'], [ui]
But I get [abc], [def], [gh\], [, ] etc.
Is it possible? Thanks in advance
PHP Code: Using negative lookbehind
$s = "'abc', 'def', 'ghf\\\\', 'jkl\'f'";
echo "$s\n";
if (preg_match_all("~'.*?(?<!(?:(?<!\\\\)\\\\))'~", $s, $arr))
var_dump($arr[0]);
OUTOUT:
array(4) {
[0]=>
string(5) "'abc'"
[1]=>
string(5) "'def'"
[2]=>
string(7) "'ghf\\'"
[3]=>
string(8) "'jkl\'f'"
}
Live Demo: http://ideone.com/y80Gas
Yes, those matches are possible.
But if you mean to ask whether it's possible to get what's inside the quotes, the easiest here would be to split by comma (through a CSV parser preferably) and trim any trailing spaces.
Otherwise, you could try something like:
\'((?:\\\'|[^\'])+)\'
Which will match either \' or a non-quote character, but will fail against stuff like \\'...
A longer, and slower regex you might use for this case is:
\'((?:(?<!\\)(?:\\\\)*\\\'|[^\'])+)\'
In PHP:
preg_match_all('/\'((?:(?<!\\)\\\'|[^\'])+)\'/', $text, $match);
Or if you use double quotes:
preg_match_all("/'((?:(?<!\\\)\\\'|[^'])+)'/", $text, $match);
Not sure why there's an error with (?<!\\) (I really mean one literal backslash) when it should be working fine. It works if the pattern is changed to (?<!\\\\).
ideone demo
EDIT: Found a simpler, better, faster regex:
preg_match_all("/'((?:[^'\\]|\\.)+)'/", $text, $match);
<?php
// string to extract data from
$string = "'abc', 'def', 'gh\'', 'ui'";
// make the string into an array with a comma as the delimiter
$strings = explode(",", $string);
# OPTION 1: keep the '
// or, if you want to keep that escaped single quote
$replacee = ["'", " "];
$strings = str_replace($replacee, "", $strings);
$strings = str_replace("\\", "\'", $strings);
# OPTION 2: remove the ' /// uncomment tripple slash
// replace the single quotes, spaces, and the backslash
/// $replacee = ["'", "\\", " "];
// do the replacement, the $replacee with an empty string
/// $strings = str_replace($replacee, "", $strings);
var_dump($strings);
?>
Instead you should use str_getcsv
str_getcsv("'abc', 'def', 'gh\'', 'ui'", ",", "'");

Delete first 3 characters and last 3 characters from String PHP

I need to delete the first 3 letters of a string and the last 3 letters of a string. I know I can use substr() to start at a certain character but if I need to strip both first and last characters i'm not sure if I can actually use this. Any suggestions?
Pass a negative value as the length argument (the 3rd argument) to substr(), like:
$result = substr($string, 3, -3);
So this:
<?php
$string = "Sean Bright";
$string = substr($string, 3, -3);
echo $string;
?>
Outputs:
n Bri
Use
substr($var,1,-1)
this will always get first and last without having to use strlen.
Example:
<?php
$input = ",a,b,d,e,f,";
$output = substr($input, 1, -1);
echo $output;
?>
Output:
a,b,d,e,f
As stated in other answers you can use one of the following functions to reach your goal:
substr($string, 3,
-3) removes 3 chars from start and end
trim($string, ",") removes all specific chars from start and end
ltrim($string, ".") removes all specific chars from start
rtrim($string, ";") removes all specific chars from end
It depends on the amount of chars you need to remove and if the removal needs to be specific. But finally substr() answers your question perfectly.
Maybe someone thinks about removing the first/last char through string dereferencing. Forget that, it will not work as null is a char as well:
<?php
$string = 'Stackoverflow';
var_dump($string);
$string[0] = null;
var_dump($string);
$string[0] = null;
var_dump($string);
echo ord($string[0]) . PHP_EOL;
$string[1] = '';
var_dump($string);
echo ord($string[1]) . PHP_EOL;
?>
returns:
string(13) "Stackoverflow"
string(13) "tackoverflow"
string(13) "tackoverflow"
0
string(13) "ackoverflow"
0
And it is not possible to use unset($string[0]) for strings:
Fatal error: Cannot unset string offsets in /usr/www/***.php on line **
substr($string, 3, strlen($string) - 6)
I don't know php, but can't you take the length of the string, start as position 3 and take length-6 characters using substr?
$myString='123456789';
$newString=substr($myString,3,-3);

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