# Recipe 1.3. Replacing Substrings

#### 1.3.1. Problem

You 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

Use substr_replace(), as in Example 1-15.

##### Replacing a substring with substr_replace( )

 `// 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. Discussion

Without 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:

`print substr_replace('My pet is a blue dog.','fish.',12); print substr_replace('My pet is a blue dog.','green',12,4); \$credit_card = '4111 1111 1111 1111'; print substr_replace(\$credit_card,'xxxx ',0,strlen(\$credit_card)-4); My pet is a fish. My pet is a green dog. xxxx 1111`

If \$start is negative, the new substring is placed at \$start characters counting from the end of \$old_string, not from the beginning:

`print substr_replace('My pet is a blue dog.','fish.',-9); print substr_replace('My pet is a blue dog.','green',-9,4); My pet is a fish. My pet is a green dog.`

If \$start and \$length are 0, the new substring is inserted at the start of \$old_string:

`print substr_replace('My pet is a blue dog.','Title: ',0,0); Title: My pet is a blue dog.`

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. Example 1-16 displays the first 25 characters of a message with an ellipsis after it as a link to a page that displays more text.

##### Displaying long text with an ellipsis

 `\$r = mysql_query("SELECT id,message FROM messages WHERE id = \$id") or die(); \$ob = mysql_fetch_object(\$r); printf('%s', \$ob->id, substr_replace(\$ob->message,' ...',25));`

The more-text.php page referenced in Example 1-16 can use the message ID passed in the query string to retrieve the full message and display it.

Documentation on substr_replace( ) at http://www.php.net/substr-replace.

PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon