Follow me on Twitter to receive updates, free scripts and ongoing announcements!

PHP string manipulation

Written by Codes Tips on July 28, 2009 – 2:53 pm -

This is a first part of PHP string manipulation.
It’s extremelly useful to know how to manipulate strings in PHP. This tutorial will guide you through how to use the functions that PHP offers.
A string in PHP it’s defined in php in a variable assigning a single or double quote value like:
$string = ‘This is a test string’;
$string = “This is a test string”;

Make all letters from string lowercase

To make every letter of a string in lowercase you should use the function strtolower like this:

<?
$string= "This is a  strtolower Function Test";
echo strtolower($string);
?>

The ouput will be: this is a strtolower function test

Make all letters of a string uppercase

You should use the function strtoupper in order to make every letter of the string in uppercase:

<?
$string= "This is a  strtoupper Function Test";
echo strtoupper($string);
?>

The ouput of will be: THIS IS A STRTOUPPER FUNCTION TEST

Capitalize first letter of each word in a sentence with ucwords

To make a sentence more estetic we can capitalize first letter of each word in a sentence with the function ucwords().

<?
$string= "This is a  ucwords Function Test";
echo ucwords($string);
?> 
Output: This Is A Ucwords Function Test

This function touch only the first letter of each word and leave other characters like they are. We can improve the way how the string is displayed by combining with the strtolower function.

<?
$string= "ThiS is a  ucwords FunctioN Test";
echo ucwords(strtolower($string));
?>

Output will be:This Is A Ucwords Function Test

Remove tabs,spaces,new lines from beginning and end of a string

To remove spaces,tabs and new lines from the beginning and end of a string you should use the function trim(). This function accepts as an input a string, that will be cleaned and returns a string without spaces,tabs and new lines.

<?
$string= "\t \nThis is a  trim Function Test   ";
echo trim($string);
?>

Output: This is a trim Function Test

Remove spaces,tabs and new lines from begining of a string

Similar like trim we can use ltrim to remove spaces,tabs and new lines from the beginning of a string

<?php
$string= "\t \nThis is a  trim Function Test \t\t  ";
echo ltrim($string);
?>

Output: This is a trim Function Test

Remove spaces,tabs and new lines from the end of a string

Similar like ltrim we can use rtrim to remove characters that we don’t need:

<?
$string= "\t \nThis is a  rtrim Function Test \t\t  ";
echo rtrim($string);
?>

Remove tags from a string

To remove tags from a string you should use strip_tags to have a clean string without tags

<?php
$string= "<pre>This is a  trim Function Test</ pre>";
echo strip_tags($string);
?>

PHP string manipulation - part 2


Tags: ,
Posted in Codes, PHP/MYSQL | 1 Comment »

Plugintaylor.com - Plugintaylor and Admin Panel