PHP - String functions

0 votes
956 views
added Apr 24, 2018 in PHP by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
//Get the length of a string
//The PHP strlen() function returns the length of a string.

//Code below returns the length of the string "Hello Lazacode!"

<?php
 echo strlen("Hello Lazacode!"); // outputs 15
?>

9 Responses

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// Count the number of words in a string with str_word_count() function 

<?php
 echo str_word_count("Hello Lazacode!"); // outputs 2
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// Reverse a string with strrev() function  

<?php
 echo strrev("Hello Lazacode!"); // outputs !edocazaL olleH
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// Replace text within a string with str_replace() function  

<?php
 echo str_replace("Lazacode", "Hormart", "Hello Lazacode!"); // outputs Hello Hormart!
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// addcslashes() function. E.g Add a backslash in front of the character "L":

<?php 
$str = addcslashes("Hello Lazacode!","L");
echo($str); 
//output Hello \Lazacode!
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// substr_count() Function used for count the number of times certain word i.e lazacode occurs in the string.

<?php
echo substr_count("Hello Lazacode. The Lazacode is the best code reference site. Everybody loves Lazacode","Lazacode");
// output 3
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// trim() function use for remove characters from string 

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
//output Hello World!
//output llo Worl
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// substr_replace() Function

<?php
echo substr_replace("Hello","world",0); 
// 0 will start replacing at the first character in the string
?>

 

0 votes
responded Apr 24, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// limiting text to 350 and strip the HTML

<?php echo substr(strip_tags($description),0,350); ?>

 

0 votes
responded May 15, 2018 by LC Marshal Captain (25,790 points)
edited Jul 20, 2018 by LC Marshal
// truncate long sentence, limit character of sentence 

<a href="<?php print $row['path']; ?>">
<?php $f_title = $row['body']; print  strlen( $f_title) > $char_limit ? substr( $f_title,0,$char_limit)."..." :  $f_title; ?>
</a>

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...