remove a part at the end of string - last match only [duplicate] - php

This question already has answers here:
Remove a part of a string, but only when it is at the end of the string
(8 answers)
Closed 12 months ago.
I'm using rtrim() to remove a part at the end of string, , US in my example:
<?php
$str = "Hello - world, c., US, US";
echo rtrim($str,", US");
?>
Output:
Hello - world, c.
It removed , US, US and i want to remove the last one only and the output should be Hello - world, c., US
How i can do that please?

rtrim() doesn't remove a specific string, it uses the string as a list of characters to remove at the end.
Use a regular expression replacement:
echo preg_replace('/, US$/', '', $str);
The $ anchors the match to the end of the string.

substr + strrpos approach:
$str = "Hello - world, c., US, US";
echo substr($str, 0, strrpos($str, ", US"));
The output:
Hello - world, c., US

Related

preg_replace() not working for repeating words [duplicate]

This question already has answers here:
php regex word boundary matching in utf-8
(4 answers)
Closed 5 years ago.
I would like to replace each occurence of hello with bye in a sentence or paragraph.
$sentence = 'nothello hello hello hello hello hello';
$find = 'hello';
$replace = 'bye';
$str = preg_replace('/(^|[\s])'.$find.'([\s]|$)/', '$1'.$replace.'$2', $sentence);
echo $str;
I want this to echo nothello bye bye bye bye bye but instead I get nothello bye hello bye hello bye.
What am I doing wrong?
I can't use \b because I am using lots of languages.
*Edit
I guess \b can work if you use the u flag.
This the right place to use zero-length assertions called lookahead and lookbehind instead of matching:
$str = preg_replace('/(?<=^|\s)'.$find.'(?=\s|$)/', $replace, $sentence);
//=> bye bye bye bye bye
More on lookarounds in regex
(?=...) is positive lookahead and (?<=...) is positive lookbehind.
You current regex search translate into this:
(^|[\s])hello([\s]|$)
which will match a string start with "hello " -- which match the first hello.
or the string " hello " or end with " hello" (a white space before the hello) which will match the 3rd and the last.
if don't need regex search/replace use str_replace as suggested before. If you need to use regex, use a regex test tool/site like https://regex101.com/ to test your regex more closely.
$sentence = 'nothello hello hello hello hello hello';
$find = 'hello';
$replace = 'bye';
$str = preg_replace('/(^|[\s])'.$find.'([\s]#i|$)/', '$1'.$replace.'$2', $sentence);
echo $str;
you need the "#i" to replace it through the whole string

Strip commas from a string in PHP [duplicate]

This question already has an answer here:
Cannot work out a php str_replace() to remove comma [closed]
(1 answer)
Closed 2 years ago.
I have the following string:
Input:
$str = "I want to remove only comma from this string, how ?";
I want to remove commas from $str, I'm new in programming and I don't understand how regex works.
use str_replace.
Example
$str = "I want to remove only comma from this string, how ?";
$str = str_replace(",", "", $str);
Explaination
As you can see there is 3 arguments we pass in str_replace
"," => this one is what you want to replace
"" => this one is value that will replace first argument value. we pass blank so it will replace comma to blank
this one is string where you want to replace.
Regex: (?<!\d)\,(?!\d)
(\,|\.) for matching exact either , or .
(?!\d) should not contains digits ahead.
(?<!\d) should not contains digit behind.
PHP code:
<?php
$str = "I want to remove only comma from this string, how. ? Here comma and dot 55,44,100.6 shouldn't be removed";
echo preg_replace("/(?<!\d)(\,|\.)(?!\d)/", "", $str);
Output:
I want to remove only comma from this string how ? Here comma 55,44,100 shouldn't be removed

Preg Match to find count of exact word in string [duplicate]

This question already has an answer here:
how to use regex special characters in pattern in preg_replace
(1 answer)
Closed 3 years ago.
I want to find the number of words in a string. I used the below regex to do the same.
$count_keys = preg_match_all('/\bs.c.\b/', $str);
Here $str is the string from which we need to found the number of occurance of the word s.c , But i am getting wrong result say if their is a word #ssc or #sssc they are also counted as well. Please guide me where I am doing the mistake or please give the correct regex code to do the same.
Try this:
$str = 'this is a s.c good to check s.c ';
echo $count_keys = preg_match_all('/\bs\.c/', $str);
Output:
2
use substr_count() instead of preg_match_all
this is the tutorials
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);
// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);
// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10);
// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
I believe the problem is your regular expression. If you are looking for occurrences of "s.c" try this:
$count_keys = preg_match_all('/\bs\.c\b/', $str);
You were missing a "\" before the "." which caused a problem because "." matches any character (except newlines) in regular expressions.
However, if you are looking for occurrences of "s.c." then try this:
$count_keys = preg_match_all('/\bs\.c\.\b/', $str);

Remove last characters of strings using regex [duplicate]

This question already has answers here:
PHP substring extraction. Get the string before the first '/' or the whole string
(14 answers)
Closed 12 months ago.
I need to find a way in PHP to remove the last portions of 2 strings using regex's. This way once they are stripped of the extra characters I can find a match between them. Here is an example of the type of string data I am dealing with:
categories_widget-__i__
categories_widget-10
So I would like to remove:
-__i__ from the first string
-10 from the second string
Thanks in advance.
(.*)-
This simple regex can do your job if - is the splitting criteria
See demo.
http://regex101.com/r/rX0dM7/7
$str1 = "categories_widget-__i__";
$str2 = "categories_widget-10";
$arr1 = explode("-", $str1);
$arr2 = explode("-", $str2);
echo $arr1[0];
echo $arr2[0];
Is the last occurrence of a hyphen the only thing that's important? If so you don't need regex:
$firstPart = substr($str, 0, strrpos($str, '-'));
ยป example
You could try the below code to remove all the characters from - upto the last.
<?php
$text = <<<EOD
categories_widget-__i__
categories_widget-10
EOD;
echo preg_replace("~-.*$~m","",$text);
?>
Output:
categories_widget
categories_widget
- matches the literal - symbol. And .* matches any character following the - symbol upto the end of the line. $ denotes the end of a line. By replacing all the matched characters with an empty string would give you the desired output.

Remove a word at the beginning of a string [duplicate]

This question already has answers here:
Remove a string from the beginning of a string
(10 answers)
Closed 9 years ago.
$str = "hello world, what's up";
How can I check $str to see if there is a word "hello" and remove it only if it is at the beginning of the string (first 5 letters)?
You can use substr, which is faster than preg_replace:
$str = "hello world, what's up?";
$pre = "hello ";
if(substr($str, 0, strlen($pre)) === $pre)
$str = substr($str, strlen($pre));
echo $str; // world, what's up?
^ indicates the beginning of the string, and an i flag for a case-insensitive match as per #Havenard's comment.
preg_replace('/^hello/i', '', $str);
preg_replace('/^hello\b/U', '', $str);
This will replace 'hello' in 'hello world' but not in 'helloworld'. Because it's replacing just one instance at the start of the string, the amount of cpu use is negligible.

Categories