Count how many numbers appears in a string - php

I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.
From a string like:
fdsji2092mds1039m
It returns that there's 8 numbers inside.

You can use filter_var() with the FILTER_SANITIZE_NUMBER_INT constant, then check the length of the new string. The new string will contain only numbers from that string, and all other characters are filtered away.
$string = "j3987snmj3j";
$numbers = filter_var($string , FILTER_SANITIZE_NUMBER_INT);
$length = strlen($numbers); // 5
echo "There are ".$length." numbers in that string";
Note that each number will be counted individually, so 137 would return 3, as would 1m3j7.
Live demo

Other solution:
function countNumbers(string $string) {
return preg_match_all('/\d/', $string, $m);
}
You can use regular expression

Try like this:
$myString = 'Som3 Charak1ers ar3 N0mberZ h3re ;)';
$countNumbers = strlen((string)filter_var($myString, FILTER_SANITIZE_NUMBER_INT));
echo 'Your input haz ' . $countNumbers . ' digits in it, man';
You can also make a function out of this to return only the number, if you need it.

Following code does what you intend to do:
<?php
$string = 'dsfds98fsdfsdf8sdf908f9dsf809fsd809f8s15d0d';
$splits=str_split($string);
$count=0;
foreach ($splits as $split){
if(is_numeric($split)){
$count++;
}
}
print_r($count);
Output: 17

Related

Using PHP preg_replace match result in a math operation?

I want to find a number in a string, add one to it, and replace it. These don't work:
$new_version =
preg_replace("/str\/(\d+)str/", "str/".("$1"+1)."str", $original);
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(intval("$1")+1)."str", $original);
Where 'str' is a very identifiable string, each side of the number (and does not contain numbers).
I realise I can do this in more than one line of code quite easily but it seems like this should be possible.
Using a callback function allows you to cast a match to number and increment, e.g.:
preg_replace_callback(
"/str\/(\d+)str/",
function($matches) { return "str/" . ((int)$matches[1] + 1) . "str"; },
$original
);
Solely using str_replace you can get the number from the string, add one to it, and the replace the old number with the new one :
$str = 'In My Cart : 11 items';
$nb = preg_replace('/\D/', '', $str);
$nb += 1;
$str = str_replace($nb-1, $nb, $str);
echo $str;

Get all numeric before first Alpha in PHP String

I'm trying to get all numeric before space/alpha in PHP string.
Example:
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
How do I can get all the number of a string just like example above?
I've an idea to get the position of first Alpha, then get all numeric before that position.
I've successfully get the position using
preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
But I'm not done yet to get the numeric before the posisition.
How do I can do that, or anybody know how to fix my idea?
Anyhelp will be appreciated.
You don't need to use regex for strings like the examples you've shown, or any functions at all for that matter. You can just cast them to ints.
$number = (int) $firstStr; // etc.
The PHP rules for string conversion to number will handle it for you.
However, because of those rules, there are some other types of strings that this won't work for. For example, '-12 Car' or '412e2 8all'.
If you do use a regex, be sure to anchor it to the beginning of the string with ^ or it will match digits anywhere in the string as the other regex answers here do.
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
Here's an extremely hackish approach that will work in most situations:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
$input = '100Pen';
if (preg_match('~(\d+)[ a-zA-Z]~', $input, $m)) {
echo $m[1];
}
This function will do the job!
<?php
function getInt($str){
preg_match_all('!\d+!', $str, $matches);
return $matches[0][0];
}
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
echo 'firstStr = '.getInt($firstStr).'<br>';
echo 'secondStr = '.getInt($secondStr).'<br>';
echo 'thirdStr = '.getInt($thirdStr);
?>

Extract numbers from string, put them in array and replace with text in one function?

I have string that looks like this: |​6|​7|​8|​9|​10|​13|​20|​22​|. I need to turn this string into array of numbers and then based on the numbers return different text strings. I managed to create this code that basicaly do what I need.
Problem that I have is that I need to execute only one function on the other side that will take string as input and give me text based on numbers in array as output. Could someone please help me with this?
function extract_numbers($string)
{
preg_match_all('/([\d]+)/', $string, $match);
return $match[0];
}
$numbers_array = extract_numbers($string);
if (in_array("6", $numbers_array)) {
return "Got Irix";
}
if (in_array("22", $numbers_array)) {
return "Got mac";
}
Maybe you may try this (a little confused about your question)
// Map numbers and text
$text = array(6 => 'Airbag 2X', 22 => 'Airbag 8X');
// Explode numbers
$numbers = explode('|', '6|22');
// Check if number exists and then echo it.
if(in_array(22, $numbers)) echo $text[22]; // Airbag 8X
You may also use a loop to print out all the numbers:
foreach($numbers as $number) echo $text[$number] . '<br />';
Output:
Airbag 2X
Airbag 8X

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

How can we split a sentence

I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!

Categories