Are you first timer at lazacode.org? Why not join us and start exchange your knowledge with everyone. Register today!

PHP - String functions

0 votes
8 views
added Apr 24 in PHP by LC Marshal First Warrant Officer (8,170 points)

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 examples

0 votes
responded Apr 24 by LC Marshal First Warrant Officer (8,170 points)

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 by LC Marshal First Warrant Officer (8,170 points)

Reverse a string with strrev() function  

<?php
 echo strrev("Hello Lazacode!"); // outputs !edocazaL olleH
?>
0 votes
responded Apr 24 by LC Marshal First Warrant Officer (8,170 points)

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 by LC Marshal First Warrant Officer (8,170 points)

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 by LC Marshal First Warrant Officer (8,170 points)

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 by LC Marshal First Warrant Officer (8,170 points)

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 by LC Marshal First Warrant Officer (8,170 points)

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 by LC Marshal First Warrant Officer (8,170 points)

limiting text to 350 and strip the HTML

<?php echo substr(strip_tags($description),0,350); ?>
0 votes
responded 6 days ago by LC Marshal First Warrant Officer (8,170 points)

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 based Knowledge Exchange Platform, where you can share your finding or solution with other members of community.
...