Re: preg_replace() help
| From: | Daniel Brown | Date: | Fri, 13 Jul 2007 21:15:35 +0000 |
| Subject: | Re: preg_replace() help | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-258820@lists.php.net to get a copy of this message | ||
On 7/13/07, Rick Pasotto <rick@niof.net> wrote:
I have quotes like the following: $txt = 'A promise is a debt. -- Irish Proverb'; I'd like to replace all the spaces afer the '--' with This is what I've tried:If you mean that EVERY space after the -- separator should be replaced, then just try this: <? $txt = "As a rule, kids with meningitis don't smile when looking at attractive faces -- not even you, Miss America, or the ravishing pharmacist I mentioned above. -- ER Questions and Answers, Part 3"; function replace_space($txt) {$pat = '/( --.*)(\s|\n)/U'; $rpl = '$1$2 '; while (preg_match($pat,$txt,$matches) > 0) { print "$txt\n"; printf("[0]: <%s>\n",$matches[0]); printf("[1]: <%s>\n",$matches[1]); printf("[2]: <%s>\n",$matches[2]); preg_replace($pat,$rpl,$txt); }The prints are for debugging. $matches contains what I expect but nothing gets replaced and $txt stays the same so it loops forever. What am I doing wrong? -- "Everyone is as God has made him, and oftentimes a great deal worse."-- Miguel De Cervantes Rick Pasotto rick@niof.net http://www.niof.net-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
$field = explode("--",$txt);
for($i=0;$i<(count($field)-1);$i++) $new_txt .= $field[$i];
$new_txt .= "--".str_replace(" "," ",$field[(count($field)-1)]);
return $new_txt;
}
echo replace_space($txt)."\n";
?>
This would print:
A promise is a debt. -- Irish ProverbConversely, it will still properly handle the existence of double-hyphens anywhere else in the quote, but not the source. Consider this string:
"As a rule, kids with meningitis don't smile when looking atattractive faces -- not even you, Miss America, or the ravishing pharmacist I mentioned above. -- ER Questions and Answers, Part 3" This would still become:
"As a rule, kids with meningitis don't smile when looking atattractive faces -- not even you, Miss America, or the ravishing pharmacist I mentioned above. -- ER Questions and Answers, Part 3" However, if you have double-hyphens in the source, like so:
"What a pain in the butt this would be! -- Me, sending anexample -- to you The phrase would be printed like this:
"What a pain in the butt this would be! -- Me, sending anexample -- to you -- Daniel P. Brown [office] (570-) 587-7080 Ext. 272 [mobile] (570-) 766-8107