how to convert camel case to upper english words in php - php

I have different strings that are function names like
createWebsiteManagementUsers
I want to change them into
Create Website Mangement Users
How can i achieve that in PHP?

a) You can use ucwords():-
echo ucwords($string);
Output:- https://3v4l.org/sCiEJ
b) In your expected outcome spaces are there, if you want that then do:
echo ucwords(implode(' ',preg_split('/(?=[A-Z])/', 'createWebsiteManagementUsers')));
Output:- https://3v4l.org/v3KUK

Use below code to solve:
$String = 'createWebsiteManagementUsers';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
echo ucwords($Words);
//output will be Create Website Mangement Users

try this
$data = preg_split('/(?=[A-Z])/', 'createWebsiteManagementUsers');
$string = implode(' ', $data);
echo ucwords($string);
output will be
Create Website Management Users

Here is what you need. This has the spaces as well!
function parseCamelCase($camelCaseString){
$words_splited = preg_split('/(?=[A-Z])/',$camelCaseString);
$words_capitalized = array_map("ucfirst", $words_splited);
return implode(" ", $words_capitalized);
}
Thanks

function camelCaseToString($string)
{
$pieces = preg_split('/(?=[A-Z])/',$string);
$word = implode(" ", $pieces);
return ucwords($word);
}
$name = "createWebsiteManagementUsers";
echo camelCaseToString($name);

May be you can try something like this
//Split words with Capital letters
$pieces = preg_split('/(?=[A-Z])/', 'createWebsiteManagementUsers');
$string = implode(' ', $pieces);
echo ucwords($string);
//You will get your desire output Create Website Management Users

Try this:
preg_match_all('/((?:^|[A-Z])[a-z]+)/',$str,$matches);

100% Most Efficient :
$word = 'camelCase'; // expected: Camel Case
$sentence = modifyWord($word);
function modifyWord($word)
{
$splittedWord = str_split($word);
$modifiedSentence = ucwords($splittedWord[0]);
for($i = 1; $i < count($splittedWord); $i++){
// ASCII : A => 65, Z => 90
// check if the letter is between A & Z
if(ord($splittedWord[$i]) >= 65 && ord($splittedWord[$i]) <= 90){
$modifiedSentence .= ' '.$splittedWord[$i];
}else{
$modifiedSentence .= $splittedWord[$i];
}
}
return $modifiedSentence;
}

Fixed version with UPPER letter check and symbols
<?php
$word = 'UniCredit Bank (AA)'; // expected: Camel Case
$word = 'CamelCase with space (CAPITAL_NAME) and strangEEword'; // expected: Camel Case
$sentence = modifyWord($word);
echo $sentence;
function modifyWord($word)
{
$splittedWord = str_split($word);
$modifiedSentence = ucwords($splittedWord[0]);
for($i = 1; $i < count($splittedWord); $i++){
// ASCII : A => 65, Z => 90
// check if the letter is between A & Z
$nextCapital = isset($splittedWord[$i+1]) && ord($splittedWord[$i+1]) >= 65 && ord($splittedWord[$i+1]) <= 90;
$prevCapital = isset($splittedWord[$i-1]) && ord($splittedWord[$i-1]) >= 65 && ord($splittedWord[$i-1]) <= 90;
if(ord($splittedWord[$i]) >= 65 && ord($splittedWord[$i]) <= 90 && !$nextCapital && !$prevCapital){
$modifiedSentence .= ' '.$splittedWord[$i];
}else{
$modifiedSentence .= $splittedWord[$i];
}
}
return $modifiedSentence;
}

Related

Php format string with pattern

I have a string (trimmed) and I would like to split this string according to a predefined pattern. I wrote a code which is probably more interpretive.
$string="123456789";
$format=['XXX','XX','XXXX'];
$formatted="";
foreach ($format as $cluster){
$formattedCluster=substr($string,0,strlen($cluster));
$string=substr($string,strlen($cluster));
$formatted.=$formattedCluster.' ';
}
$formatted=substr($formatted, 0, -1);
dd($formatted);
//outputs: "123 45 6789"
As you can see it takes a string without any whitespace, and separates it with whitespaces according to a pattern $format in this case. The pattern is an array.
A pseudo example:
$str='qweasdzxc'
$pattern=['X','X','XXXX','XXX']
$formatted='q w easd zxc'; //expected output
It works as expected but it is rather hideous. What is the correct solution to this problem? By correctness, I mean speed and readability.
Environment:
Php 7.4,
Laravel 8
I would use https://www.php.net/manual/en/function.vsprintf.php do get the result:
$str='qweasdzxc';
$pattern='% % %%%% %%%'; // ['X','X','XXXX','XXX']
echo vsprintf(str_replace('%', '%s', $pattern), str_split($str));
$string = "qweasdzxc";
$chunks = array(1,1,4,3);
// Optional check to ensure that $string can be divided into requested chunks
if(array_sum($chunks) <> strlen($string)) {
echo "String length does not fit requested chunks.";
}
$i=0;
$output = "";
foreach($chunks as $chunk) {
$output .= substr($string,$i,$chunk) . " ";
$i += $chunk;
}
echo rtrim($output);
// Outputs "q w easd zxc"
Probably an easier way to remove the whitespace from the right hand end by not adding it in the first place based on whether or not it's the last element of the array, but that does the trick.
easy way to use preg_match try this.
$data = '11234567890';
if(preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $data, $matches))
{
$result = $matches[1] . ' ' .$matches[2] . ' ' . $matches[3];
echo $result;
}
I don't think it's what you expected but:
function format_number($number) {
$number_size = strlen($number);
if (9 != $number_size) {
return $number;
}
$step = 0;
$formated = '';
foreach (range(0, 9) as $i => $n) {
if (isset($number[$n])) {
switch ($step) {
case 0:
case 1:
case 3:
case 5:
case 6:
case 7:
case 8:
$formated .= $number[$n];
break;
case 2:
case 4:
$formated .= $number[$n] . ' ';
break;
}
$step++;
}
}
return $formated;
}
Working only for the pattern XXX XX XXXX

PHP Ucwords with or and special characters

Here is what I'm doing.
I have a couple of strings that is uppercase
†HELLO THERE
DAY OR NIGHT
So to convert them, I'm using the following code:
ucwords(strtolower($string));
Here is the end result:
†hello There
Day Or Night
How can I ignore the † or any special characters so it the words can show
†Hello There
and how can I keep words like or all lowercase.
Try:
print preg_replace_callback('#([a-zA-ZÄÜÖäüö0-9]+)#',function($a){
return ucfirst(strtolower($a[0]));
},
'†hello THERE'
);
[a-zA-ZÄÜÖäüö0-9]+ find a word that only has this chars
You can also use this instead [\w]+
see: http://www.regular-expressions.info/wordboundaries.html
preg_replace_callback call a function on the found result
function($a){} do something with the result, here ucfirst(strtolower())
$lowerString = strtolower($string);
$stringArray = explode($lowerString, ' ');
foreach ($stringArray as $key => $singleString) {
$i = 0;
$formatedString = '';
$upcased = false;
for ($i; $i < strlen($singleString); $i++) {
$ascNum = chr($singleString[$i]);
$word = $singleString[$i];
if (!$upcased) {
if (($ascNum >= 65 && $ascNum <= 90) || ($ascNum >= 97 && $ascNum <= 122) ) {
$word = ucwords($word);
$upcased = true;
}
}
$formatedString .= $word;
}
$stringArray[$key] = $formatedString;
}
$result = implode(' ',$stringArray);
maybe a little complicated, but a clean idea.
ucwords(strtolower("†HELLO THERE"),"† "); the second parameter of ucwords is an optional delimiter. So by including both dagger and space, ucwords will work for the examples provided.
for your second question, see here
Assuming words are separated by a space:
<?php
function custom_ucfirst($s)
{
$s = strtolower($s);
$e = (strpos($s, ' ') !== false ? explode(' ', $s) : array($s));
$keep_all_lowercase = array('or','and','but');
foreach($e as $k=>$v)
{
if(!in_array($v, $keep_all_lowercase))
{
$str_split = str_split($v);
foreach($str_split as $k2=>$v2)
{
if(in_array($v2, range('a','z')))
{
$str_split[$k2] = strtoupper($v2);
break;
}
}
$e[$k] = implode('', $str_split);
}
}
return implode(' ', $e);
}
echo custom_ucfirst('†HELLO THERE .cloud. or sky what a nice an*d ()good day.');
// †Hello There .Cloud. or Sky What A Nice An*d ()Good Day.

How to find the place value for the given decimal value through php?

I'm not so familiar with php, but i know we could find the place value of a given number through php. For example if the input is 23.56 it should echo 2 - Tens, 3 - Ones, 5 - Hundredths, 6 - Thousandths.
Any idea would be appreciated. :) please help.
Try
$str = '23.56';
$strdiv = explode('.', $str);
$before = array('Tens', 'Ones');
$after = array('Hundredths', 'Thousandths');
$counter = 0;
foreach($strdiv as $v) {
for($i=0; $i<strlen($v); $i++) {
if(!empty($v)) {
if($counter == 0) {
$newarr[] = substr($v,$i, 1).' - '.$before[$i];
}
if($counter == 1) {
$newarr[] = substr($v,$i, 1).' - '.$after[$i];
}
}
}
$counter++;
}
echo implode(', ',$newarr); //2 - Tens, 3 - Ones, 5 - Hundredths, 6 - Thousandths
<?php
$mystring = '123.64';
$findme = '.';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of '.' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Another method:
$num = 23.56;
$arr = array("Tens","Ones","Hundredths","Thousandths");
$num = str_replace(".","",$num);
for ($i=0;$i<strlen($num);$i++) {
$res[] = $num[$i] ." - ".$arr[$i];
}
echo implode(', ',$res);
Answer for all writers:
1) Dont use for in php! Dont use! Use foreach but dont use for! Why? php stored all array keys as STRING its very slow!
$arr = array('a', 'b', 'c');
var_dump($arr[0] === $arr['0']); // true
2) Your solutions in three lines:
function humanityFloat($v) {
$out = str_split(str_replace('.', '', sprintf('%01.2f', (float) $v)));
array_walk($out, function(&$a, $i, $s) { $a .= ' - ' . $s[$i]; }, array('Tens', 'Ones', 'Hundredths', 'Thousandths'));
return join(', ', $out);
}
echo humanityFloat(22) . PHP_EOL;
Of course this function not check input parameters - this example. But example return valid result for all unsigned float or decimal numbers between 10 and 99.99

Validate IBAN PHP

As designing a new platform we tried to integrate the IBAN numbers. We have to make sure that the IBAN is validated and the IBAN stored to the database is always correct. So what would be a proper way to validate the number?
As the logic was explained in my other question, I've created a function myself. Based on the logic explained in the Wikipedia article find a proper function below. Country specific validation.
Algorithm and character lengths per country at https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN.
function checkIBAN($iban)
{
if(strlen($iban) < 5) return false;
$iban = strtolower(str_replace(' ','',$iban));
$Countries = array('al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24);
$Chars = array('a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35);
if(array_key_exists(substr($iban,0,2), $Countries) && strlen($iban) == $Countries[substr($iban,0,2)]){
$MovedChar = substr($iban, 4).substr($iban,0,4);
$MovedCharArray = str_split($MovedChar);
$NewString = "";
foreach($MovedCharArray AS $key => $value){
if(!is_numeric($MovedCharArray[$key])){
if(!isset($Chars[$MovedCharArray[$key]])) return false;
$MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
}
$NewString .= $MovedCharArray[$key];
}
if(bcmod($NewString, '97') == 1)
{
return true;
}
}
return false;
}
Slight modification of #PeterFox answer including support for bcmod() when bcmath is not available,
<?php
function isValidIBAN ($iban) {
$iban = strtolower($iban);
$Countries = array(
'al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,
'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,
'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,
'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,
'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24
);
$Chars = array(
'a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,
'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35
);
if (strlen($iban) != $Countries[ substr($iban,0,2) ]) { return false; }
$MovedChar = substr($iban, 4) . substr($iban,0,4);
$MovedCharArray = str_split($MovedChar);
$NewString = "";
foreach ($MovedCharArray as $k => $v) {
if ( !is_numeric($MovedCharArray[$k]) ) {
$MovedCharArray[$k] = $Chars[$MovedCharArray[$k]];
}
$NewString .= $MovedCharArray[$k];
}
if (function_exists("bcmod")) { return bcmod($NewString, '97') == 1; }
// http://au2.php.net/manual/en/function.bcmod.php#38474
$x = $NewString; $y = "97";
$take = 5; $mod = "";
do {
$a = (int)$mod . substr($x, 0, $take);
$x = substr($x, $take);
$mod = $a % $y;
}
while (strlen($x));
return (int)$mod == 1;
}
The accepted answer is not the preferred way of validation. The specification dictates the following:
Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid
Replace the two check digits by 00 (e.g. GB00 for the UK)
Move the four initial characters to the end of the string
Replace the letters in the string with digits, expanding the string as necessary, such that A or a = 10, B or b = 11, and Z or z = 35. Each alphabetic character is therefore replaced by 2 digits
Convert the string to an integer (i.e. ignore leading zeroes)
Calculate mod-97 of the new number, which results in the remainder
Subtract the remainder from 98, and use the result for the two check digits. If the result is a single digit number, pad it with a leading 0 to make a two-digit number
I've written a class that validates, formats and parses strings according to the spec. Hope this helps some save the time required to roll their own.
The code can be found on GitHub here.
top rated function does NOT work.
Just try a string with '%' in it...
I'm using this one :
function checkIBAN($iban) {
// Normalize input (remove spaces and make upcase)
$iban = strtoupper(str_replace(' ', '', $iban));
if (preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $iban)) {
$country = substr($iban, 0, 2);
$check = intval(substr($iban, 2, 2));
$account = substr($iban, 4);
// To numeric representation
$search = range('A','Z');
foreach (range(10,35) as $tmp)
$replace[]=strval($tmp);
$numstr=str_replace($search, $replace, $account.$country.'00');
// Calculate checksum
$checksum = intval(substr($numstr, 0, 1));
for ($pos = 1; $pos < strlen($numstr); $pos++) {
$checksum *= 10;
$checksum += intval(substr($numstr, $pos,1));
$checksum %= 97;
}
return ((98-$checksum) == $check);
} else
return false;
}
I found this solution in cakephp 3.7 validation class. Plain beautiful php realization.
/**
* Check that the input value has a valid International Bank Account Number IBAN syntax
* Requirements are uppercase, no whitespaces, max length 34, country code and checksum exist at right spots,
* body matches against checksum via Mod97-10 algorithm
*
* #param string $check The value to check
*
* #return bool Success
*/
public static function iban($check)
{
if (!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $check)) {
return false;
}
$country = substr($check, 0, 2);
$checkInt = intval(substr($check, 2, 2));
$account = substr($check, 4);
$search = range('A', 'Z');
$replace = [];
foreach (range(10, 35) as $tmp) {
$replace[] = strval($tmp);
}
$numStr = str_replace($search, $replace, $account . $country . '00');
$checksum = intval(substr($numStr, 0, 1));
$numStrLength = strlen($numStr);
for ($pos = 1; $pos < $numStrLength; $pos++) {
$checksum *= 10;
$checksum += intval(substr($numStr, $pos, 1));
$checksum %= 97;
}
return ((98 - $checksum) === $checkInt);
}
This function check the IBAN and need GMP activate http://php.net/manual/en/book.gmp.php.
function checkIban($string){
$to_check = substr($string, 4).substr($string, 0,4);
$converted = '';
for ($i = 0; $i < strlen($to_check); $i++){
$char = strtoupper($to_check[$i]);
if(preg_match('/[0-9A-Z]/',$char)){
if(!preg_match('/\d/',$char)){
$char = ord($char)-55;
}
$converted .= $char;
}
}
// prevent: "gmp_mod() $num1 is not an integer string" error
$converted = ltrim($converted, '0');
return strlen($converted) && gmp_strval(gmp_mod($converted, '97')) == 1;
}
enjoy !

Truncate a string to first n characters of a string and add three dots if any characters are removed

How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
Update 2:
Or as function:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
This functionality has been built into PHP since version 4.0.6. See the docs.
echo mb_strimwidth('Hello World', 0, 10, '...');
// outputs Hello W...
Note that the trimmarker (the ellipsis above) are included in the truncated length.
The Multibyte extension can come in handy if you need control over the string charset.
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
$string = mb_substr($string, 0, $length - 3, $charset) . '...';
}
sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.
eg:
we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.
phew, am bad at explaining, here is the code.
class Fun {
public function limit_text($text, $len) {
if (strlen($text) < $len) {
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word) {
if ((strlen($word) > $len) && $out == null) {
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len) {
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
If you want to cut being careful to don't split words you can do the following
function ellipse($str,$n_chars,$crop_str=' [...]')
{
$buff=strip_tags($str);
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return $buff;
}
if $str is shorter than $n_chars returns it untouched.
If $str is equal to $n_chars returns it as is as well.
if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
NOTE: be aware that this method will remove all tags in case of HTML.
The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html
(just read the word_limiter and character_limiter sections).
Here's two functions from it relevant to your question:
if ( ! function_exists('word_limiter'))
{
function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return rtrim($matches[0]).$end_char;
}
}
And
if ( ! function_exists('character_limiter'))
{
function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
}
}
}
}
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
Use substring
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
I'm not sure if this is the fastest solution, but it looks like it is the shortest one:
$result = current(explode("\n", wordwrap($str, $width, "...\n")));
P.S. See some examples here https://stackoverflow.com/a/17852480/131337
This function do the job without breaking words in the middle
function str_trim($str,$char_no){
if(strlen($str)<=$char_no)
return $str;
else{
$all_words=explode(" ",$str);
$out_str='';
foreach ($all_words as $word) {
$temp_str=($out_str=='')?$word:$out_str.' '.$word;
if(strlen($temp_str)>$char_no-3)//-3 for 3 dots
return $out_str."...";
$out_str=$temp_str;
}
}
}
The function I used:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
See it in action.
This is what i do
function cutat($num, $tt){
if (mb_strlen($tt)>$num){
$tt=mb_substr($tt,0,$num-2).'...';
}
return $tt;
}
where $num stands for number of chars, and $tt the string for manipulation.
I developed a function for this use
function str_short($string,$limit)
{
$len=strlen($string);
if($len>$limit)
{
$to_sub=$len-$limit;
$crop_temp=substr($string,0,-$to_sub);
return $crop_len=$crop_temp."...";
}
else
{
return $string;
}
}
you just call the function with string and limite
eg:str_short("hahahahahah",5);
it will cut of your string and add "..." at the end
:)
To create within a function (for repeat usage) and dynamical limited length, use:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
It's best to abstract you're code like so (notice the limit is optional and defaults to 10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
substr() would be best, you'll also want to check the length of the string first
$str = 'someLongString';
$max = 7;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...';
}
wordwrap won't trim the string down, just split it up...
$width = 10;
$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
or with wordwrap
$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
this solution will not cut words, it will add three dots after the first space.
I edited #Raccoon29 solution and I replaced all functions with mb_ functions so that this will work for all languages such as arabic
function cut_string($str, $n_chars, $crop_str = '...') {
$buff = strip_tags($str);
if (mb_strlen($buff) > $n_chars) {
$cut_index = mb_strpos($buff, ' ', $n_chars);
$buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
}
return $buff;
}
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
while(strlen($yourString) > 22) {
$pos = strrpos($yourString, " ");
if($pos !== false && $pos <= 22) {
$out = substr($yourString,0,$pos);
break;
} else {
$yourString = substr($yourString,0,$pos);
continue;
}
}
} else {
$out = $yourString;
}
echo "Output String: ".$out;
If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
In this case, $preview will be "Knowledge is a natural right of every human being".
Live code example:
http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

Categories