Search in a php string for a count of numbers - php

I have variables like this:
Example 1: 709000-037602-14-5_ABC
Example 2: 702000-025801-12_4_DEF
Example 3: 210104-1041-011866_GHI
How can i cut the data?
My idea is to seach for the underscore BUT the example 1 does cut on the false segment.
I want to get this variables: $var=709000-037602-14-4, $var=709000-037602-14_4 and $var1=210104-1041-011866
(ABC, DEF, GHI are not important. I only wanted to show i cant search for it.)
For now my used function is:
$var= strstr($var_original, '_', true);
Question: Can I count the number of numbers on the secound sequment (037602, 025801 or 1041) because this is 6 OR 4 digits.
Thanks for help :)

You can use:
explode
array_pop
implode
Like:
$string = '709000-037602-14-5_ABC';
$string1 = '702000-025801-12_4_DEF';
echo explodeCode($string).'<br>'. explodeCode($string1);
function explodeCode($code){
$final = explode('_', $code);
array_pop($final);
return (count($final) === 2) ? implode('_', $final) : implode('', $final);
}
Output:
709000-037602-14-5
702000-025801-12_4
After your multiple example i suppose is better use preg_split like:
$string = '709000-037602-14-5_ABC';
$string1 = '702000-025801-12_4_DEF';
$string2 = '709000-037602-14-5_ABC_test_no1';
echo explodeCode($string).'<br>'. explodeCode($string1). '<br>'. explodeCode($string2);
function explodeCode($code){
return preg_split("/\_[A-Z]/", $code)[0];
}
Output:
709000-037602-14-5
702000-025801-12_4
709000-037602-14-5

Related

Count how many numbers appears in a string

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

How to sort words in alphabetical order from a sentence, not array

I'm trying to take sentences from a user and storing them to compare them later, but i want them to be alphabetial, like;
Apple
Banana
taken from a string like, "Banana, Oranges And Apples"; So before that i first cut the words i don't want but i don't know how I'll go about sorting since PHP sort() seems to only work on array
<?php
$str = 'Man Methord Wifi HOlla Teddy Husband';
$result = trim( preg_replace(
"/[^a-z0-9']+([a-z0-9']{1,5}[^a-z0-9']+)*/i",
" ",
" $str "
) );
$lower_str = strtolower ($result);
echo $lower_str;
?>
This function may work for you :
function sortstring($string,$unique = false) {
$string = str_replace('.', '', $string);
$array = explode(' ',strtolower($string));
if ($unique) $array = array_unique($array);
sort($array);
return implode(' ',$array);
}
You can find this function and its example usage at http://www.wordinn.com/solution/226/php-sort-words-sentences
It has got an easy function that is called sort().In sort function, there are many type of different sort algorithms working on sort function.This function has got 2 parameters.First parameter of sort function is array which will be sort and Second one is about type of sort algorithm.
<?php
$data = array("a","k","b","z","i","v");
sort($data,SORT_STRING);
print_r($data);
?>

PHP adding the value 1 to a position in an string and replace

I want to replace a letter with another character and also add 1 value more.
I mean the values are dynamic
For example I have H9 ,i want to replace as G10 .
Similarly...
H2 as G3
H6 as G7
Is it possible to use str_replace() for this ?
I got this one which works for me:
$old_string = "H2";
$new_string = "G" . (substr($old_string, 1) + 1);
echo $new_string;
Works fine for me. This is just for one value, but i guess you can loop through an array too, just have to modify the values like this
foreach($old_values as $v) {
$new_values[] = "G" . (substr($v, 1) + 1);
}
So you could save all the values into the $new_string array
Try This
<?php
$str = "H25";
preg_match_all('!\d+!', $str, $matches);
$str = str_replace($matches['0']['0'], $matches['0']['0']+1, $str, $count);
echo $str;
?>
Of course you can use str_replace()
Use
$new = array("G10", "G3", "G7");
$old = array("H9", "H2", "H6");
$string = str_replace($old, $new, $string);
where $string is your original string.
More simpler way... (Generalized Solution)
<?php
$str='G10';
preg_match('!\d+!', $str, $digit); //<---- Match the number
$str = substr($str,0,1); //<--- Grab the first char & increment it in the second line
echo ++$str.($digit[0]+1); //"prints" H11
Demo

preg_replace php to replace repeated characters

So I have a list of values like that goes like this:
values: n,b,f,d,e,b,f,ff`
I want to use preg_replace() in order to remove the repeated characters from the list of values (it will be inserted to a MySQL table). b and f are repeated. ff should not count as f because it's a different value. I know that \b \b will be used for that. I am not sure on how to take out the repeated b and f values as well as the , that precedes each value.
If the list is in a string looking like the example above, a regex is overkill. This does it just as well;
$value = implode(',', array_unique(explode(',', $value)));
I agree with other commenters that preg_replace is not the way to go; but, since you ask, you can write:
$str = preg_replace('/\b(\w+),(?=.*\b\1\b)/', '', $str);
That will remove all but the last instance of a given list-element.
No need for regex for this:
join(",", array_unique(split(",", $values)))
If this list you're dealing with is a simple string, a possible solution would be like this:
function removeDuplicates($str) {
$arr = explode(',', $str);
$arr = array_unique($arr);
return implode(',', $arr);
}
$values = removeDuplicates('n,b,f,d,e,b,f,ff'); // n,b,f,d,e,ff
$str = "values: n,b,f,d,e,b,f,ff";
$arr = array();
preg_match("/(values: )([a-z,]+)/i", $str, $match);
$values = explode(",", $match[2]);
foreach($values AS $value){
if(!$arr[$value]) $arr[$value] = true;
}
$return = $match[1];
foreach($arr AS $a){
$return .= ($i++ >= 1 ? "," : "").$a;
}

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