str_word_count and Arabic text - php

I used the function str_word_count to count how many ARABIC words are in a text, but it returns zero:
$sentence = 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ';
$countSentence = str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';
Thanks in advance

Try to use this function
if (!function_exists('utf8_str_word_count')){
function utf8_str_word_count($string, $format = 0, $charlist = null) {
if ($charlist === null) {
$regex = '/\\pL[\\pL\\p{Mn}\'-]*/u';
}
else {
$split = array_map('preg_quote',
preg_split('//u',$charlist,-1,PREG_SPLIT_NO_EMPTY));
$regex = sprintf('/(\\pL|%1$s)([\\pL\\p{Mn}\'-]|%1$s)*/u',
implode('|', $split));
}
switch ($format) {
default:
case 0:
// For PHP >= 5.4.0 this is fine:
return preg_match_all($regex, $string);
// For PHP < 5.4 it's necessary to do this:
// $results = null;
// return preg_match_all($regex, $string, $results);
case 1:
$results = null;
preg_match_all($regex, $string, $results);
return $results[0];
case 2:
$results = null;
preg_match_all($regex, $string, $results, PREG_OFFSET_CAPTURE);
return empty($results[0])
? array()
: array_combine(
array_map('end', $results[0]),
array_map('reset', $results[0]));
}
}
}
Example
$sentence = 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ';
$countSentence = utf8_str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';

Related

What's wrong with preg_match_all and my string?

I have a series of tag in the text that I want to match with preg_match_all but the $regex string has something wrong and I can't understand what to do.
$tagReplace = ['mov', 'flv', 'youtube'];
foreach ($tagReplace as $plg_tag) {
$regex = "#{" . $plg_tag . "}(.*?){/" . $plg_tag . "}#s";
$var = preg_match_all($regex, "{mov}the_video_url{/mov}", $matches, PREG_PATTERN_ORDER);
var_dump($matches);
}
<?php
$matches = array();
$p = '/(mov|flv|youtube)/';
$replace_to = 'your text you want to be insted of the mov or flv or youtube';
$str = ' the string that you want to work on and replace its content';
$p_c = array(
$p => function($match) {
$ret = str_replace("mov", $replace_to, $match[0]);
$ret = str_replace("flv", $replace_to, $ret);
$ret = str_replace("youtube", $replace_to, $ret);
return $ret;
}
);
$res3 = preg_replace_callback_array($p_c, $str);

Processing text in PHP finding a matching character

How can I process text with some codes.
So suppose I have text as below
Hello {::first_name::} {::last_name::},
How are you?
Your organisation is {::organisation::}
For any text between {:: and ::} should be evaluated to get its value.
I tried exploding text to array using space as delimiter and then parsing array items to look for "{::" and if found get string between "{::" and "::}" and calling database to get this field value.
So basically these will be db fields.
Below is the code I have tried
$msg = "Hello {::first_name::} {::last_name::},
How are you?
Your organisation is {::organisation::}";
$msg_array = explode(" ", $msg);
foreach ($msg_array as $str) {
if (strpos($str, "{::") !== false) {
$field_str = get_string_between($str, "{::", "::}");
$field_value = $bean->$field_str; //Logic that gets the value of the field
$msgStr .= $field_value . " ";
} else {
$msgStr .= $str . " ";
}
}
function get_string_between($string, $start, $end)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
Your script seems fine. Your script in fiddle
If you are looking for alternative way, you can try using preg_match_all() with str_replace(array, array, source)
<?php
$bean = new stdClass();
$bean->first_name = 'John';
$bean->last_name = 'Doe';
$bean->organisation = 'PHP Company';
$string = "Hello {::first_name::} {::last_name::}, How are you? Your organisation is {::organisation::}";
// find all placeholders
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$placeholders = $matches[0];
//strings inside placeholders
$parts = $matches[1];
// return values from $bean by matching object property with strings inside placeholders
$replacements = array_map(function($value) use ($bean) {
// use trim() to remove unexpected space
return $bean->{trim($value)};
}, $parts);
echo $newstring = str_replace($placeholders, $replacements, $string);
Short format:
$string = "Hello {::first_name::} {::last_name::}, How are you? Your organisation is {::organisation::}";
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$replacements = array_map(function($value) use ($bean) {
return $bean->{trim($value)};
}, $matches[1]);
echo str_replace($matches[0], $replacements, $string);
And if you prefer to use a function:
function holder_replace($string, $source = null) {
if (is_object($source)) {
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$replacements = array_map(function($value) use ($source) {
return (property_exists(trim($value), 'source')) ? $source->{trim($value)} : $value;
}, $matches[1]);
return str_replace($matches[0], $replacements, $string);
}
return $string;
};
echo holder_replace($string, $bean);
OUTPUT:
Hello John Doe, How are you? Your organisation is PHP Company
fiddle
Or you can simply use str_replace function:
$data = "{:: string ::}";
echo str_replace("::}", "",str_replace("{::", "", $data));

echo $string does not print array elements while string returned by a function

How to get this
function render($string, $array)
{
$pattern = '/[^{{=]*[\w][}}$]/';
preg_match_all($pattern, $string, $matches);
foreach($matches as $tt)
{
$index = '';
foreach($tt as $match1){
$match = str_replace('}', '', $match1);
if (strpos($match,'.') !== false)
{
$string_parts = explode('.', $match);
//print_r($string_parts);
foreach($string_parts as $part)
{
$index .="['".$part."']";
}
}
else
{
$index ="['".$match."']";
}
//echo '$array'.$index;
$new_str = str_replace("{{=".$match."}}", '{$array'.$index.'}' , $string);
$index = '';
//echo $new_str;
$string = $new_str;
}
}
return $string;
}
$arr = [
'site'=>'smartprix',
'users'=>[
['name'=>'user1', 'contact'=>'1234'],
['name'=>'user2', 'contect'=>'4321']
],
'location'=>['address'=>['pincode'=>'123456', 'city'=>'Noida'],
'near'=>'mamura']
];
$array = $arr;
//echo "{$array['site']}"; //It is printing smartprix
$string = "{{=site}} is located at pincode {{=location.address.pincode}}";
echo render($string, $array);
// it is printing "{$array['site']} is located at pincode {$array['location']['address']['pincode']}" why it not convert $array['site'] into the value. I read on php manual and got some reference that {} do not work on returned string then what is the method so that i can print array values after returning the string ?
You can print your expected string is.
echo $string = $array['site']." is located at pincode ".$arr['location']['address']['pincode'];

PHP how to find uppercase in array

I have an array with many words, but some senteces are in uppercase. For example:
THIS SENTENCE IS UPPERCASE
this sentece is in lowercase
And I want to split this two sentences by \r\n, but I cant find how to do it
Here is how I retrive this array:
$result_pk_info = array();
while ($row = odbc_fetch_array($sql_pk_info))
{
$opisanie = iconv("cp1257", "UTF-8", trim($row['opis']));
$id = iconv("cp1257", "UTF-8", trim($row['pacientid']));
$date = iconv("cp1257", "UTF-8", trim($row['data']));
$desc = explode('##$', $opisanie);
$all_info = "<tr><td>".$desc[1]."</td></tr>";
$result_pk_info[] = $all_info;
}
in $desc I have words array in which I want to search and split uppercase and lowercase.
So can anyone help me with it?
UPD the text which I have hase something like this structure:
SENTENCE IN UPPERCASE Sentece in lower case
This function is what you're looking for :
function split_upper_lower ($string)
{
$words = explode (' ', $string);
$i = 0;
foreach ($words as $word)
{
if (ctype_upper ($word))
$new_string_array[++$i]['type'] = 'UPPER';
else
$new_string_array[++$i]['type'] = 'LOWER';
$new_string_array[$i]['word'] = $word;
}
$new_string = '';
foreach ($new_string_array as $key => $new_word)
{
if (!isset ($current_mode))
{
if (ctype_upper ($new_word))
$current_mode = 'UPPER';
else
$current_mode = 'LOWER';
}
if ($new_word['type'] === $current_mode)
{
$new_string .= $new_word['word'];
if (isset ($new_string_array[$key + 1]))
$new_string .= ' ';
}
else
{
$new_string .= "\r\n" . $new_word['word'];
if (isset ($new_string_array[$key + 1]))
$new_string .= ' ';
if ($current_mode === 'UPPER') $current_mode = 'LOWER';
else $current_mode = 'UPPER';
}
}
return $new_string;
}
Tested it with br :
$string = 'HI how ARE you doing ?';
echo split_upper_lower ($string);
Output :
HI
how
ARE
you doing ?
Use preg_match: http://php.net/manual/en/function.preg-match.php
$string = 'THIS SENTENCE IS UPPERCASE';
$string2 = 'this sentece is in lowercase';
if(preg_match ( '/[A-Z ]$/' , $string))
{
echo 'uppercase';
}
else
{
echo 'lowercase';
}
Use this in your loop through $desc. Where $string is one element of an array containing one string.
/[A-Z ]$/ will match all uppercase with spaces. You can just upgrade your regexp to grab something else from strings.
If I understood your question you can do like this ...
$desc = array ("abcd","ABCD","bbb","B");
foreach($desc as $value) {
if(ctype_upper($value)) {
// character is upper
} else {
// character is lower
}
}
This can be done using preg_match_all(). Use the following code,
$result_pk_info = array();
while ($row = odbc_fetch_array($sql_pk_info))
{
$opisanie = iconv("cp1257", "UTF-8", trim($row['opis']));
$id = iconv("cp1257", "UTF-8", trim($row['pacientid']));
$date = iconv("cp1257", "UTF-8", trim($row['data']));
$desc = explode('##$', $opisanie);
//converting $desc array to string
$string = implode(" " , $desc);
//Upper case Matching
$upprCase = preg_match_all('/[A-Z]/', $string, $uprmatches, PREG_OFFSET_CAPTURE);
if($upprCase){
foreach ($uprmatches as $match)
{
foreach($match as $value)
//Iam a uppercase
print $UpperCase = $value[0];
}}
//Splitting with \r\n
print "\r\n";
//lower case matching
$lowrCase = preg_match_all('/[a-z]/', $string, $lowrmatches, PREG_OFFSET_CAPTURE);
if($lowrCase){
foreach ($lowrmatches as $match)
{
foreach($match as $value)
//Iam a lowercase
print $lowerCase = $value[0];
}}
}

Php substr entire words

How can i substr 20 chars from $xbio and get only complete words?
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
TY
Found this searching stackoverflow - tell me what do you think please:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>
This is the function i always use:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}
preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];
This is a function that i use for this kind of task:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}

Categories