PHP Strings

Strings are sequences of characters used to store and manipulate text. PHP provides a variety of functions for working with strings, making it easy to create, modify, and manipulate text content.


1. Creating Strings


Single Quoted Strings:

The simplest way to create a string. It does not interpret variables or special characters (except for \\ and \').

Example
<!DOCTYPE html>
<html>
<body>
<?php
echo 'This is a simple string \n john.';
?>
</body>
</html>

Try it yourself

Double Quoted Strings:

More flexible. They parse variables and escape sequences like \n (newline).

Example
<!DOCTYPE html>
<html>
<body>
<?php
$name = "John";
$string = "Hello, $name";
$newline = "Line 1\nLine 2";
$str = 'This is a \'simple\' string';
echo $string."<br>";
echo $newline."<br>";
echo $str;
?>
</body>
</html>

Try it yourself


Common String Functions


  • strlen(): Returns the length of a string.


Example
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello World!"); // Outputs: 12
?>
</body>
</html>

Try it yourself

  • str_word_count(): Returns counts the number of words in a string.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo str_word_count("Hello world!");
?>
</body>
</html>

Try it yourself

  • strpos(): Finds the position of the first occurrence of a substring in a string.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$position = strpos("Hello World", "World"); // Outputs: 6
echo $position;
?>
</body>
</html>

Try it yourself

  • substr(): Returns a portion of a string.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$substring = substr("Hello World", 0, 5); // Outputs: Hello
echo $substring;
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.