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);
Related
I have a string that has a number inside exactly one pair of quotes. How can I get this number using php?
I have tried iterating over the string and or using str_split but I'm not sure how to limit it to what is inside the quotation marks. The fact that the number can be any length makes it even harder.
EDIT: Here is an example
Hello this is my "100"th string!,
I would need to return 100;
echo intval('123string');
results in 123
preg_match() is a way to get the number from string. Example:
$str = 'Hello this is my "100"th string!,';
preg_match('/\d+/', $str, $match);
echo $match[0];
Demo
use preg_replace:
echo preg_replace("~[^\d+]~", '', 'Hello this is my "100"th string!,');
trim the quotes from around the string, and php will immediately see the number inside.
$str = "'1234'";
$num = trim($str, "'\"");
echo $num + 1;
// => 1235
or if you have text as well a string, replace all non-digits with spaces, then have
php automatically parse the string when it is used in an arithmetic expression.
$num = preg_replace('/\D/', ' ', $string) + 0;
I'm having trouble knowing how many times that the - character is in front of my string.
Some examples:
$string = "-Lorem Ipsum"; // 1
$string = "--Lorem Ipsum"; // 2
$string = "---Lorem Ipsum"; // 3
$string = "--Lorem-Ipsum"; // 2
But how can I find this? I know you can search the number of occurrences of a character in a string. But I want the number of - characters before an alphabet letter. Not all the sequences (see last example).
How should I approach this?
You can use the old school trick of using a string as an array here as such:
$search="-";
$i=0;
while($string[$i]==$search)
{
$i++;
}
echo "Found $i instances at the start of the string.";
What about using ltrim() and strlen()
echo strlen($string) - strlen(ltrim($string, "-"));
See example at eval.in
it would also work -
preg_match('/(?!-)/', $string, $match, PREG_OFFSET_CAPTURE);
$match - the position of any character but - which is indeed the count of -.
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.
I have this regexp:
/(.*)(([0-9]([^a-zA-Z])*){7,}[0-9])(.*)/.
Given the following values
0654535263
065453-.-5263
065asd4535263
Expected Results
06****
06****
06****
Actual Results
0654535263
06****
065asd4535263
It does not match the last row because of the letters (I want to match from 0-3 letters) and it matches only last occurence (in the second row in example, it skips first row).
First of all thank u all oyur answers are very helpfull and i owe u a bih time. I cant create array of numbers and mask them like that because i can have string like this:
I am John, I live bla bla my phone is: 0, 6, 5, 4, 5, 3, 5, 2, 6 - 3 -- 065asd4535263.
To simplify i want to hide entered mobile number.
I had two problems:
change regxp mentioned above, to hide digits separated by no more than 3 chars.
preg_replace was replacing only one occurence.
At the end i just need regexp to replace any array of digits, at least 6 digits long, separated by any number of special chars (12--654-5, 453/--222, 23....5645 etc) OR no more than 3 chars (ltters) (06asd453, 123as562).
Thank you again, all answers are vry helpfull, but i am gulty because i didnt formulated my question right.
p.s. i cant give u reputation because i must have at least 15, as soon as i get that much, i will 'vote up', all answers deserve it.
Hmm why so complicated when you only want to mascarade your string.
$input = '0654535263';
$input = substr($input, 0, 2);
$output = $input . '********';
Its a bit easier when you only want the first 2 characters of your string. Perhaps your solution had another sin. But this is a bit easier.
You can just use substr_replace
echo substr_replace($v, "****", 2);
Example
$list = array("0654535263","065453-.-5263","065asd4535263");
echo "<pre>";
foreach ( $list as $v ) {
echo substr_replace($v, "****", 2), PHP_EOL;
}
Output
06****
06****
06****
I'm guessing that the reason you want to use regular expressions is so that you don't mask every string that you get. This regex checks that there is at least 2 digits in the beginning of the string, then 0 to 3 alphabet characters, and then all the rest of the characters of the string need to be non-alphabet characters. If it matches, it masks the string, otherwise it says the string does not match.
$string = '0654535263';
if(preg_match('~^(\d{2})\d*?[a-zA-Z]{0,3}[^a-zA-Z]*$~', $string))
$answer = preg_replace('~^(\d{2})\d*?[a-zA-Z]{0,3}[^a-zA-Z]*$~', '$1****', $string);
else
$answer = $string . ' does not match';
print_r($answer); // 06****
I found this solution on stackoverflow for getting the first word from a sentence.
$myvalue = 'Test me more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test
However, this case takes ' ' (a space) as the divider. Does anyone know how to get the first word from a string if you do not know what the divider is? It can be ' ' (space), '.' (full stop), '.' (or comma). Basically, how do you take anything that is a letter from a string up to the point where there is no letter?
E.g.:
'House, rest of sentence here' would give 'House'
'House.' would also give 'House'
'House thing' would also give 'House'
Thanks!
There is a string function (strtok) which can be used to split a string into smaller strings (tokens) based on some separator(s). For the purposes of this thread, the first word (defined as anything before the first space character) of Test me more can be obtained by tokenizing the string on the space character.
<?php
$value = "Test me more";
echo strtok($value, " "); // Test
?>
For more details and examples, see the strtok PHP manual page.
preg_split is what you're looking for.
$str = "bla1 bla2,bla3";
$words = preg_split("/[\s,]+/", $str);
This snippet splits the $str by space, \t, comma, \n.
Use the preg_match() function with a regular expression:
if (preg_match('/^\w*/', 'Your text here', $matches) > 0) {
echo $matches[0]; // $matches[0] will contain the first word of your sentence
} else {
// no match found
}