Separate Integer From Arabic String PHP - php

how i separate a integer number from a given string with comma separate values. I have tried but not succeeded.
$Q22V=نعم1,لا2,نعم3,لا4,نعم5,لا6,نعم7,لا8,نعم9,لا10,نعم11,لا12
list($num,$letter) = preg_split('/(?<=\d)(?=[a-z]+)/i',$Q22v);
echo "- ".$letter."<span style=float:right>$ ".$num ."</span> <br>";
I want to display result like this
نعم 1
2 لا
3 لا

$Q22V = "نعم1,لا2,نعم3,لا4,نعم5,لا6,نعم7,لا8,نعم9,لا10,نعم11,لا12";
$items = explode(',', $Q22V);
foreach($items as $item){
preg_match('/([^0-9]*)([0-9]+)/', $item, $matches);
$letter = $matches[1];
$num = $matches[2];
echo $num . ' ' . $letter . '<br/>';
}
Explode the string on , to separate the string on commas.
Then use a regular expression to separate the numbers from the non-numbers.
$num will contain the number while $letter will contain the Arabic characters.
Output should be similar to your example output.

Related

Format integer or string in php

sorry for a noob question but I am wondering if you could format strings in php with comma or dashes, something like this:
Ex. #1
Sample Input: 123456789
Formatted Output: 123,456,789 or 123-456-789
Ex. #2
Sample Input: 0123456789
Formatted Output: 012,3456,789 or 012-3456-789
If anyone could help me out, that would be appreciated.
You could use a regex replacement here:
function formatNum($input, $sep) {
return preg_replace("/^(\d{3})(\d+)(\d{3})$/", "$1".$sep."$2".$sep."$3", $input);
}
echo formatNum("123456789", ","); // 123,456,789
echo "\n";
echo formatNum("0123456789", "-"); // 012-3456-789
If it's just a case of split the initial string into 3 char segments and join them with a specific char, you can use str_split() with the number of chars you want in each segment and then implode() the result with the separator you need...
$test = '012345678';
echo implode("-", str_split($test, 3));
$number = 133456789;
$number_text = (string)$number; // convert into a string
if(strlen($number_text) %3 == 0){
$arr = str_split($number_text, "3");
// $price_new_text = implode(",", $arr);
$number_new_text = implode("-", $arr);
echo $number_new_text;
}
else{
if( preg_match( '/(\d{3})(\d{4})(\d{3})$/', $number_text, $matches ) )
{
$number_new_text = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
$number_new_text = $matches[1] . ',' .$matches[2] . ',' . $matches[3];
echo $number_new_text;
}
}

How To Count Number Of Words From Preg Match Result

I have a code that removes comma from list of words and separate all words. I tried counting the number of words in the string (which also contain mail addresses and words) from the result, but it returns 00000 instead of just 5. How do I resolve this issue. below is my code
$input = "example#k.c, bar#h.c, baz#h.c., shibbyc, poopc.";
//-- handles it all in one pass
$output = preg_split('/(,)/', $input, -1, PREG_SPLIT_NO_EMPTY);
//-- just output
array_walk($output, function(&$item, $idx) {
echo substr_count($item,$idx);
// echo $idx . ': ' . $item . PHP_EOL;
});
No need for regex, just use explode.
Much less memory hungry function.
And count off course.
$input = "example#k.c, bar#h.c, baz#h.c., shibbyc, poopc.";
$arr = explode(",", $input);
Echo count($arr); //echo 5
https://3v4l.org/SLBnc
You could just use count() :
$output = preg_split('/(,)/', $input, -1, PREG_SPLIT_NO_EMPTY);
echo count($output); // 5

count the occurrences of all the letters in a string PHP

I want to count the frequency of occurrences of all the letters in a string. Say I have
$str = "cdcdcdcdeeeef";
I can use str_split and array_count_values to achieve this.
array_count_values(str_split($str));
Wondering if there is another way to do this without converting the string to an array? Thanks
You don't have to convert that into an array() you can use substr_count() to achieve the same.
substr_count — Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars($str, 1) as $strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars — Return information about characters used in a string
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in
string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
class Strings
{
public function count_of_each_letter($string){
$string_chars = array();
$length_ = mb_strlen($string,'UTF-8');
if($length_== 0){return null;}
else{
for ($i=0; $i < $length_; $i++) {
$each_letter = mb_substr($string,0,1,'UTF-8');
$string_chars[$each_letter] = mb_substr_count($string, $each_letter);
$string = str_replace($each_letter,"", $string);
$length_ = mb_strlen($string,'UTF-8');
}
$string = '';
foreach ($string_chars as $key => $value) {
$string .= $key.'-'.$value.'<br>';
}
return $string;
}
}
}
$new_counter = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتک‌نفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسال‌هاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسی‌بی‌اسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبین‌المللیخودادامهمی‌دادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانه‌سرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
you can do it by following way as well:
$str = 'aabbbccccdddeeedfff';
$arr = str_split($str);
$result = array_count_values($arr);
$string = http_build_query($result,'','');
echo str_replace('=','',$string);

How to check if comma separated strings have duplicate values in php

I have a variable that contains comma separated strings and I would like to create a check if this variable has duplicate strings inside without converting it into an array. If it would make it any easier, each comma separated strings have 3 characters.
example.
$str = 'PTR, PTR, SDP, LTP';
logic: if any of the strings has a duplicate value then display an error.
This should work for you:
Just use strtok() to loop through each token of your string, with , as delimiter. Then use preg_match_all() to check if the token is more than once in the string.
<?php
$str = "PTR, PTR, SDP, LTP";
$tok = strtok($str, ", ");
$subStrStart = 0;
while ($tok !== false) {
preg_match_all("/\b" . preg_quote($tok, "/") . "\b/", substr($str, $subStrStart), $m);
if(count($m[0]) >= 2)
echo $tok . " found more than 1 times, exaclty: " . count($m[0]) . "<br>";
$subStrStart += strlen($tok);
$tok = strtok(", ");
}
?>
output:
PTR found more than 1 times, exaclty: 2
You are going to run into some issues with just using explode. In your example, if you use explode, you'll get:
'PTR', ' PTR', ' SDP', ' LTP'
You have to map trim in there.
<?php
// explode on , and remove spaces
$myArray = array_map('trim', explode(',', $str));
// get a count of all the values into a new array
$stringCount = array_count_values($myArray);
// sum of all the $stringCount values should equal size of $stringCount IE: they are all 1
$hasDupes = array_sum($stringCount) != count($stringCount);
?>

Return part of string

I have an array with strings like:
209#ext-local : SIP/209 State:Idle Watchers 2
208#ext-local : SIP/208 State:Unavailable Watchers 1
How can I echo the state for example Idle or Unavailable?
Thanks.
Using regex it will match any string containing letters and numbers.
$string = '209#ext-local : SIP/209 State:Idle Watchers 2';
preg_match("/State\:([A-Za-z0-9]+)/", $string, $results);
echo $results[1]; // Idle
strpos will search the string to see if it is contains the characters in that exact order.
strpos will not always work if the word idle or unavailable has the possibility to show up in any other way in the string.
You can use the php explode and parse the sting into an array of strings.
exp.
$string = "209#ext-local : SIP/209 State:Idle Watchers 2";
$string = explode(':', $string);
will give you ['209#ext-local ',' SIP/209 State','Idle Watchers 2']. Then if you explode the 3rd entry my ' ' you would get your answer.
$answer = explide(' ', $string[2]);
echo $answer[0];
Assuming your strings are all the same format, you can try splitting the string down using explode(), which returns an array of string, separated by a provided delimiter, like
foreach ($yourStrings as $s) {
$colonSplit = explode(":", $stringToSplit);
$nextStringToSplit = $colonSplit[2];
$spaceSplit = explode(" ", $nextStringToSplit);
$status = $spaceSplit[0];
echo $status;
}
May not be elegant but it should work.
Quick (and dirty) way. Assuming your array contains the full elements you listed above, the array element values do NOT contain 'idle' or 'unavailable' in any other capacity other than what you listed, and you just want to echo out the value and "is idle" or "is unavailable":
//$a being your array containing the values you listed above
foreach ($a as $status) {
if (strpos($status, "Idle") == true)
echo $status . " is idle";
elseif (strpos($status, "Unavailable") == true)
echo "$status" . " is unavailable";
}

Categories