1.3. Replacing Substrings1.3.1. ProblemYou want to replace a substring with a different string. For example, you want to obscure all but the last four digits of a credit card number before printing it. 1.3.2. Solution// Everything from position $start to the end of $old_string // becomes $new_substring $new_string = substr_replace($old_string,$new_substring,$start); // $length characters, starting at position $start, become $new_substring $new_string = substr_replace($old_string,$new_substring,$start,$length); 1.3.3. DiscussionWithout the $length argument, substr_replace( ) replaces everything from $start to the end of the string. If $length is specified, only that many characters are replaced:
If $start is negative, the new substring is placed at $start characters counting from the end of $old_string, not from the beginning:
If $start and $length are 0, the new substring is inserted at the start of $old_string:
The function substr_replace( ) is useful when you've got text that's too big to display all at once, and you want to display some of the text with a link to the rest. For example, this displays the first 25 characters of a message with an ellipsis after it as a link to a page that displays more text:
The more-text.php page can use the message ID passed in the query string to retrieve the full message and display it. 1.3.4. See AlsoDocumentation on substr_replace( ) at http://www.php.net/substr-replace.
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|