|
użytkowników online: 121
|
OPINIE UŻYTKOWNIKÓW
|
Uważam, że serwis jest najlepszy na świecie. Wykonany rzetelnie, a wszystkie skrypty sa dopracowane. Zamieszczony materiał godny mistrza. Jestem programistą od wielu lat i bez tego serwisu nie istnieje. Upraszacza życie każdemu programiście. Imponujący jest fakt, że do twórcy serwisu zawsze można się zwrócić z prośbą o pomoc i uzyskuje się ją w bardzo krótkim czasie. Najważniejsze w tym wszystkim jest to, że można korzystać z witryny za symboliczną opłatą.
Marcin Kowalski Multinet Polska
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
preg_replace (PHP 3 >= 3.0.9, PHP 4, PHP 5) preg_replace -- Perform a regular expression search and replace Opismixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit [, int &count]] )
Searches subject for matches to
pattern and replaces them with
replacement.
Replacement may contain references of the form
\\n or (since PHP 4.0.4)
$n, with the latter form
being the preferred one. Every such reference will be replaced by the text
captured by the n'th parenthesized pattern.
n can be from 0 to 99, and
\\0 or $0 refers to the text matched
by the whole pattern. Opening parentheses are counted from left to right
(starting from 1) to obtain the number of the capturing subpattern.
When working with a replacement pattern where a backreference is immediately
followed by another number (i.e.: placing a literal number immediately
after a matched pattern), you cannot use the familiar \\1
notation for your backreference. \\11, for example,
would confuse preg_replace() since it does not know whether
you want the \\1 backreference followed by a literal 1,
or the \\11 backreference followed by nothing. In this case
the solution is to use \${1}1. This creates an
isolated $1 backreference, leaving the 1
as a literal.
If subject is an array, then the search
and replace is performed on every entry of
subject, and the return value is an array
as well.
The e modifier makes preg_replace()
treat the replacement parameter as PHP code after
the appropriate references substitution is done. Tip: make sure that
replacement constitutes a valid PHP code string,
otherwise PHP will complain about a parse error at the line containing
preg_replace().
Parametry
- pattern
The pattern to search for. It can be either a string or an array with
strings.
- replacement
The string or an array with strings to replace. If this parameter is a
string and the pattern parameter is an array,
all pattens will be replaced by that string. If both
pattern and replacement
parameters are arrays, each pattern will be
replaced by the replacement counterpart. If
there are less keys in the replacement array
than in the pattern array, the excedent
patterns will be replaced by an empty string.
- subject
The string or an array with strings to search and replace.
- limit
The maximum possible replacements for each pattern in each
subject string. Defaults to
-1 (no limit).
- count
If specified, this variable will be filled with the number of
replacements done.
Zwracane wartości
preg_replace() returns an array if the
subject parameter is an array, or a string
otherwise.
If matches are found, the new subject will
be returned, otherwise subject will be
returned unchanged.
Przykłady
Przykład 1. Convert HTML to text |
<?php
$search = array ('@<script[^>]*?>.*?</script>@si', '@<[\/\!]*?[^<>]*?>@si', '@([\r\n])[\s]+@', '@&(quot|#34);@i', '@&(amp|#38);@i',
'@&(lt|#60);@i',
'@&(gt|#62);@i',
'@&(nbsp|#160);@i',
'@&(iexcl|#161);@i',
'@&(cent|#162);@i',
'@&(pound|#163);@i',
'@&(copy|#169);@i',
'@&#(\d+);@e'); $replace = array ('',
'',
'\1',
'"',
'&',
'<',
'>',
' ',
chr(161),
chr(162),
chr(163),
chr(169),
'chr(\1)');
$text = preg_replace($search, $replace, $document);
?>
|
|
Przykład 2. Using backreferences followed by numeric literals |
<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>
|
Powyższy przykład wyświetli: |
Przykład 3. Using indexed arrays with preg_replace() |
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
|
Powyższy przykład wyświetli: The bear black slow jumped over the lazy dog. |
By ksorting patterns and replacements, we should get what we wanted.
|
<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>
|
Powyższy przykład wyświetli: The slow black bear jumped over the lazy dog. |
|
Przykład 4. Replacing several values |
<?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
'/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>
|
Powyższy przykład wyświetli: |
Przykład 5. Using the 'e' modifier |
<?php
preg_replace("/(<\/?)(\w+)([^>]*>)/e",
"'\\1'.strtoupper('\\2').'\\3'",
$html_body);
?>
|
This would capitalize all HTML tags in the input text.
|
Przykład 6. Strip whitespace
This example strips excess whitespace from a string.
|
<?php
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
echo $str;
?>
|
|
Przykład 7. Using the count parameter |
<?php
$count = 0;
echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; ?>
|
Powyższy przykład wyświetli: |
NotatkiNotatka:
When using arrays with pattern and
replacement, the keys are processed in the order
they appear in the array. This is not necessarily the
same as the numerical index order. If you use indexes to identify which
pattern should be replaced by which
replacement, you should perform a
ksort() on each array prior to calling
preg_replace().
User Contributed NotesRebort
02-Feb-2006 08:51
31-Jan-2006 07:23
Uh-oh. When I looked at the text in the preview, I had to double the number of backslashes to make it look right.
I'll try again with my original text:
$full_text = preg_replace('/\[p=(\d+)\]/e',
"\"<a href=\\\"./test.php?person=$1\\\">\"
.get_name($1).\"</a>\"",
$short_text);
I hope that it comes out correctly this time :-)
leif at solumslekt dot org
31-Jan-2006 05:24
I've found a use for preg_replace. If you've got eg. a database with persons assiciated with numbers, you may want to input links in a kind of shorthand, like [p=12345], and have it expanded to a full url with a name in it.
This is my solution:
$expanded_text = preg_replace('/\\[p=(\d+)\\]/e',
"\\"<a href=\\\\\\"./test.php?person=$1\\\\\\">\\".get_name($1).\\"</a&>\\"",
$short_text);
It took me some time to work out the proper number of quotes and backslashes.
regards, Leif.
SG_01
20-Jan-2006 01:43
Re: wcc at techmonkeys dot org
You could put this in 1 replace for faster execution as well:
<?php
function removeEmptyLines($string)
{
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
}
?>
05-Jan-2006 11:09
First, I have no idea about regexp, all I did has been through trial and error,
I wrote this function which tries to clean crappy ms word html, I use it to clean user pasted code to online wysiwyg online editors from ms word.
There
|