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.
Related
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
This question already has answers here:
Count exact substring in a string in php
(3 answers)
Closed 3 years ago.
I'm trying to count the number of occurrences of a character in a string.
for example:
$string = "ab abc acd ab abd";
$chars = "ab";
How many times does $chars exactly appears in $string, and the right answer is 2 times, but with substr_count() it returns 3 times !!!
Is there any PHP function or Regex that return the right answer ?
with regex you can do the following:
$count = preg_match_all('/\bab\b/', $string);
it will count occurrencies of the word "ab". \b in the regular expression means position between a non-word character and a word character.
A "word" character is any letter or digit or the underscore character.
To what you have said in comments already, you are not trying to find an exact word since a word has specific boundaries. So what you are trying to do is something like this:
/(?:\A|[^H])HH(?:[^H]|\z)/g
preg_match_all('/(\A|[^H])HH([^H]|\z)/', $string, $matches);
or with question's example:
/(?:\A|[^a])ab(?:[^b]|\z)/g
preg_match_all('/(?:\A|[^a])ab(?:[^b]|\z)/', $string, $matches);
Explanation:
(?: \A | [^a] ) # very beginning of the input string OR a character except `a`
ab # match `ab`
(?: [^b] | \z ) # end of the input string OR a character except `b`
Live demo
Above was a simple understanding of what should be done but it's more than better to use a solution that is made for this specific purpose, named lookarounds:
/(?<!a)ab(?!b)/g
preg_match_all('/(?<!a)ab(?!b)/', $string, $matches);
There's a few ways. Regex as above, or using simple PHP instead:
$string = 'ab abc acd ab abd';
$chars = 'ab';
$strings = explode(" ", $string);
echo array_count_values($strings)[$chars];
// Outputs 2
// IF you don't have php 5.6:
$values = array_count_values($strings);
echo $values[$chars];
// Outputs 2
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);
Hi I want to remove a characters using preg_replace in php so i have this code here which i want to remove the whole characters, letters and numbers except the last digit(s) which has dash(-) symbol followed by a digits so here's my code.
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
I expect the result will be
-10
the problem is above is not working very well. I checked the pattern using http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ doesn't work at all. I don't know why but anyone who can help to to figure it out?
Thanks a lot
Here is a way to go:
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf1245-10');
Output:
-10
and
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf124510');
Output:
<nothing>
My first thinking is to use explode in this case.. make it simple like the following code.
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
An other way:
$result = preg_match('~\A.*\K-\d+\z~', $str, $m) ? $m[0] : '';
pattern details:
\A # start of the string anchor
.* # zero or more characters
\K # discard all on the left from match result
-\d+ # the dash and the digits
\z # end of the string anchor
echo preg_replace('/(\w+)(-\w+)/','$2', 'asdf1245-10');
This question already has answers here:
PHP ltrim behavior with character list
(2 answers)
Closed 12 months ago.
How to trim multiple characters at begin and end of string.
string should be something like {Hello {W}orld}.
i want to trim both { and } at begin and end.
don't want to use multiple trim function.
Use the optional second argument to trim which allows you to specify the list of characters to trim:
<?php
$str = "{Hello {W}orld}";
$str = trim($str, "{}");
echo "Trimmed: $str";
Output:
Trimmed: Hello {W}orld
Is there always a character at the beginning and at the end, that you want to remove? If so you could just use the following:
<?php
$string = '{Hello {W}orld}';
echo substr( $string, 1, strlen( $string )-2 );
?>
See: http://codepad.org/IDbG6Km2