PHP Strings

php strings

PHP Strings variables are used for values that contain character strings. A string can be used directly in a function or it can be stored in a variable.

For example

$txt="Hello World"; echo $txt; 

The output of the code
Hello World

The Concatenation Operator
There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two variables together, use the dot (.) operator

$txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2; 

Output : Hello World 1234

strpos() function

The strpos() function is used to search for a string or character within a string.
int strpos ( string $haystack , mixed $needle [, int $offset ] )
If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.

For example

echo strpos("Hello world!","world"); 

Output : 6

strlen() function

The strlen() function is used to find the length of a string.
int strlen ( string $string )

echo strlen("Hello world!"); 

Output : 12.

The length of a string is often used in loops or other functions when it is important to know when the string ends.

str_repeat() function

The str_repeat function is used to repeat a string.
string str_repeat ( string $input , int $multiplier )

echo str_repeat("-=", 10); 

Output : -=-=-=-=-=-=-=-=-=-=

str_replace() function

The str_replace function is used to replace all occurrences of the search string with the replacement string. This function returns a string or an array with the replaced values.

$phrase = "You should eat fruits, vegetables, and fiber every day."; 
$healthy = array("fruits", "vegetables", "fiber"); 
$yummy = array("pizza", "beer", "ice cream"); 
$newphrase = str_replace($healthy, $yummy, $phrase); 
echo $newphrase; 

Output : You should eat pizza, beer, fiber


You may also like...