note 92312 modified in function.preg-match-all by danbrown
| From: | danbrown@php.net | Date: | Sat, 18 Jul 2009 23:56:25 +0000 |
| Subject: | note 92312 modified in function.preg-match-all by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158463@lists.php.net to get a copy of this message | ||
Using preg_match_all I made a pretty handy function.
<?php
function reg_smart_replace($pattern, $replacement, $subject, $replacementChar = "$$$",
$limit = -1)
{
if (! $pattern || ! $subject || ! $replacement ) { return false; }
$replacementChar = preg_quote($replacementChar);
preg_match_all ( $pattern, $subject, $matches);
if ($limit > -1) {
foreach ($matches as $count => $value )
{
if ($count + 1 > $limit ) { unset($matches[$count]); }
}
}
foreach ($matches[0] as $match) {
$rep = ereg_replace($replacementChar, $match, $replacement);
$subject = ereg_replace($match, $rep, $subject);
}
return $subject;
}
?>
This function can turn blocks of text into clickable links or whatever. Example:
<?php
reg_smart_replace(EMAIL_REGEX, '<a href="mailto:$$$">$$$</a>', $description)
?>
will turn all email addresses into actual links.
Just substitute $$$ with the text that will be found by the regex. If you can't use $$$ then
use the 4th parameter $replacementChar
--was--
Using preg_match_all I made a pretty handy function.
<?php
function reg_smart_replace($pattern, $replacement, $subject, $replacementChar = "$$$",
$limit = -1)
{
if (! $pattern || ! $subject || ! $replacement ) { return false; }
$replacementChar = preg_quote($replacementChar);
preg_match_all ( $pattern, $subject, $matches);
if ($limit > -1) {
foreach ($matches as $count => $value )
{
if ($count + 1 > $limit ) { unset($matches[$count]); }
}
}
foreach ($matches[0] as $match) {
$rep = ereg_replace($replacementChar, $match, $replacement);
$subject = ereg_replace($match, $rep, $subject);
}
return $subject;
}
?>
This function can turn blocks of text into clickable links or whatever. Example:
<?
reg_smart_replace(EMAIL_REGEX, '<a href="mailto:$$$">$$$</a>', $description)
?>
will turn all email addresses into actual links.
Just substitute $$$ with the text that will be found by the regex. If you can't use $$$ then
use the 4th parameter $replacementChar
http://php.net/manual/en/function.preg-match-all.php