PHP string replace
This tutorial shows you how PHP string replace works with code examples and detailed explanation.
Tutorial info:
| Name: | PHP string replace |
| Total steps: | 1 |
| Category: | Basics |
| Date: | 2007-09-03 |
| Product: | See complete product |
Bookmark PHP string replace
Step 1 - PHP string replace
PHP string replace
One of the most important and most frequently used string manipulation in PHP is the string replace function. You can replace all sub-strings in a string or only some of them. You can limit the replace for only a part of the main string. Besides this you can make string replace with regular expressions.
PHP has the following built in string manipulation function to replace strings:
- str_replace
- str_ireplace
- preg_replace
- strtr
So let's see how to use them.
str_replace
This function replaces all occurrences of the search string with the replacement string. From PHP 5 you can limit the number of replaces as well. The syntax of str_replace is the following:
mixed str_replace ( mixed $search, mixed $replace, mixed $subject [, int &$count] )
So first you need to define a string you want to replace and as second parameter you define the new string. The last mandatory parameter is the main string itself on which you want to make the replace. Here is a string replace with str_replace example:
Code:
<?php $originalString = "I like red cars, and I have a red car near my red bike."; ?>
str_ireplace
This function is very similar to str_replace but it is case-insensitive.
preg_replace
This function performs a regular expression search and replace. The syntax is the following:
mixed preg_replace ( mixed $pattern, mixed $replacement, mixed $subject [, int $limit [, int &$count]] )
An example code:
Code:
<?php $originalString = 'September 03, 2007'; $pattern = '/(\w+) (\d+), (\d+)/i'; $replacement = '${1} 01,$3'; ?>
Tags: php string replace, string replace, php string, php replace, string, replace
| PHP string replace - Table of contents |
|---|
| Step 1 - PHP string replace |