Questions And Answers

More Tutorials

PHP Extracting/replacing substrings

Single characters can be extracted using array (square brace) syntax as well as curly brace syntax. These two syntaxes will only return a single character from the string. If more than one character is needed, a function will be required, i.e.- substr
Strings, like everything in PHP, are 0-indexed.

$foo = 'Hello world';
$foo[6]; // returns 'w'
$foo{6}; // also returns 'w'
substr($foo, 6, 1); // also returns 'w'
substr($foo, 6, 2); // returns 'wo'

Strings can also be changed one character at a time using the same square brace and curly brace syntax. Replacing more than one character requires a function, i.e.- substr_replace

$foo = 'Hello world';
$foo[6] = 'W'; // results in $foo = 'Hello World'
$foo{6} = 'W'; // also results in $foo = 'Hello World'
substr_replace($foo, 'W', 6, 1); // also results in $foo = 'Hello World'
substr_replace($foo, 'Whi', 6, 2); // results in 'Hello Whirled'

// note that the replacement string need not be the same length as the substring replaced


In this page (written and validated by ) you learned about PHP Extracting replacing substrings . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Splitting a string.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.