PHP.mk документација

preg_replace

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.preg-replace.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.preg-replace.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
preg_replace

Референца за `function.preg-replace.php` со подобрена типографија и навигација.

function.preg-replace.php

preg_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_replaceИзврши пребарување и замена со регуларен израз

= NULL

preg_replace(
         string|array $pattern,
         string|array $replacement,
         string|array $subject,
         int $limit = -1,
         int &$count = null
): string|array|null

Пребарувања subject Скенира pattern и ги заменува со replacement.

За да совпаднете точен стринг, наместо шема, разгледајте ја употребата на str_replace() or str_ireplace() наместо оваа функција.

Параметри

pattern

Шемата за пребарување. Може да биде низа или низа со низи.

Неколку PCRE модификатори се исто така достапни.

replacement

Стрингот или низа со стрингови за замена. Ако овој параметар е стринг и pattern параметарот е низа, сите шеми ќе бидат заменети со тој стринг. Ако и двата pattern and replacement параметри се низи, секој pattern ќе биде заменет со replacement соодветниот. replacement Ако има помалку елементи во pattern низата отколку во patternнизата, било кој дополнителен

replacement ќе биде заменет со празен стринг. \n or $nможе да содржи референци во форма n, при што втората форма е преферирана. Секоја таква референца ќе биде заменета со текстот фатен од n 'тата родителска шема. \0 or $0 може да биде од 0 до 99, и string литералите можеби ќе треба да се избегнат.

Кога работите со шема за замена каде што референцата е веднаш проследена со друг број (т.е.: ставање литерален број веднаш по соодветниот шаблон), не можете да ја користите познатата \1 нотација за вашата референца. \11, на пример, би збунило preg_replace() бидејќи не знае дали сакате \1 референца проследена со литерален 1, или \11 референца проследена со ништо. Во овој случај решението е да се користи ${1}1. Ова создава изолирана $1 референца, оставајќи го 1 како литерал.

subject

Низата или низа со низи за пребарување и замена.

Враќа subject е низа, тогаш пребарувањето и заменувањето се врши на секој запис од subject, а вратената вредност е исто така низа.

Ако subject низата е асоцијативна, клучевите ќе бидат зачувани во вратената вредност.

limit

Максимални можни замени за секоја шема во секоја subject низа. Стандардно е -1 (нема ограничување).

count

Ако е специфицирано, оваа променлива ќе биде пополнета со бројот на извршени замени.

Вратени вредности

preg_replace() враќа низа ако subject параметарот е низа, или стринг во спротивно.

Ако се најдат совпаѓања, новиот subject ќе биде вратен, во спротивно subject ќе биде вратен непроменет или null аргумент, или

Errors/Exceptions

Користењето на модификаторот "\e" е грешка; се емитува E_WARNING во овој случај.

Ако дадениот регуларен израз не може да се состави во валиден регуларен израз, еден E_WARNING се емитува.

Примери

Пример #1 Користење референци проследени со бројчени литерали

<?php
$string
= 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo
preg_replace($pattern, $replacement, $string);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

April1,2003

Пример #2 Користење индексирани низи со preg_replace()

<?php
$string
= 'The quick brown fox jumps over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo
preg_replace($patterns, $replacements, $string);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

The bear black slow jumps over the lazy dog.

Со сортирање на обрасци и замени, треба да го добиеме она што го сакавме.

<?php
$string
= 'The quick brown fox jumps over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
ksort($patterns);
ksort($replacements);
echo
preg_replace($patterns, $replacements, $string);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

The slow black bear jumps over the lazy dog.

Пример #3 Замена на неколку вредности

<?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');
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

$startDate = 5/27/1999

Пример #4 Отстрани празни места

Овој пример отстранува вишок празни места од стринг.

<?php
$str
= 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>

Пример #5 Користење на count parameter

<?php
$count
= 0;

echo
preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo
$count; //3
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

xp***to
3

Белешки

Забелешка:

Кога користите низи со pattern and replacement, клучевите се обработуваат по редоследот по кој се појавуваат во низата. Ова е не нужно исто како редоследот на нумеричките индекси. Ако користите индекси за да идентификувате кои pattern треба да се замени со кои replacement, треба да извршите ksort() на секоја низа пред да го повикате preg_replace().

Забелешка:

Кога и двете pattern and replacement се низи, правилата за совпаѓање ќе работат последователно. Тоа е, вториот pattern/replacement пар ќе работи на стринг што произлегува од првиот pattern/replacement пар, а не оригиналниот стринг. Ако сакате да симулирате замени што работат паралелно, како што е менување на две вредности, заменете еден образец со посреднички заменски знак, а потоа во подоцнежен пар заменете го тој посреднички заменски знак со посакуваната замена.

<?php
$p
= array('/a/', '/b/', '/c/');
$r = array('b', 'c', 'd');
print_r(preg_replace($p, $r, 'a'));
// prints d
?>

Види Исто така

  • — Parle\ParserException класа
  • preg_quote() - Квотирајте знаци за регуларни изрази
  • preg_filter() - Изврши пребарување и замена на регуларни изрази
  • preg_match() - Изврши совпаѓање со регуларен израз
  • preg_replace_callback() - Изврши пребарување и замена со регуларен израз со користење на повици
  • preg_split() - Подели стринг по регуларен израз
  • preg_last_error() - Враќа код за грешка од последното извршување на PCRE регуларен израз
  • str_replace() - Замени ги сите појави на низата за пребарување со низата за замена

Белешки од корисници 10 белешки

arkani at iol dot pt
пред 17 години
Because i search a lot 4 this:

The following should be escaped if you are trying to match that character

\ ^ . $ | ( ) [ ]
* + ? { } ,

Special Character Definitions
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
More Special Character Stuff
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
Even More Special Characters
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
Анонимен
пред 2 години
You can only use numeric backreferences in the replacement string, but not named ones:
<?php 
echo preg_replace('#(\d+)#', '\1 $1 ${1}', '123');
// 123 123 123
echo preg_replace('#(?<digits>\d+)#', '\digits $digits ${digits}', '123');
// \digits $digits ${digits}
?>

To use named backreferences, you have to use preg_replace_callback:
<?php
echo preg_replace_callback('#(?<digits>\d+)#', function( $m ){
  return "$m[1] $m[digits] {$m['digits']}";
}, '123');
// 123 123 123

echo preg_replace_callback('#(?<digits>\d+)#', fn($m) => "$m[1] $m[digits] {$m['digits']}", '123');
// 123 123 123
?>

See https://bugs.php.net/bug.php?id=81469
nik at rolls dot cc
пред 13 години
To split Pascal/CamelCase into Title Case (for example, converting descriptive class names for use in human-readable frontends), you can use the below function:

<?php
function expandCamelCase($source) {
  return preg_replace('/(?<!^)([A-Z][a-z]|(?<=[a-z])[^a-z]|(?<=[A-Z])[0-9_])/', ' $1', $source);
}
?>

Before:
  ExpandCamelCaseAPIDescriptorPHP5_3_4Version3_21Beta
After:
  Expand Camel Case API Descriptor PHP 5_3_4 Version 3_21 Beta
razvan_bc на yahoo точка com
3 години пред
How to replace all comments inside code without remove crln  = \r\n or cr \r each line?

<?php
$txt_target=<<<t1
this;//    dsdsds
    nope
    
/*
    ok
    */
is;huge
/*text bla*/
    /*bla*/
 
t1;

/*
=======================================================================
expected result:
=======================================================================
this;
    nope

is;huge
=======================================================================
visualizing in a hex viewer .. to_check_with_a_hex_viewer.txt ...
 t  h  i  s  ; LF TAB n  o  p  e CR LF CR LF  i  s  ;  h  u  g  e CR LF
74 68 69 73 3b 0a 09 6e 6f 70 65 0d 0a 0d 0a 69 73 3b 68 75 67 65 0d 0a
I used F3 (viewer + options 3: hex) in mythical TOTAL COMMANDER!
=======================================================================
*/

echo '<hr><pre>';
echo  $txt_target;
echo '</pre>';

//  a single line '//' comments
$txt_target = preg_replace('![ \t]*//.*[ \t]*!', '', $txt_target);

//  /* comment */
$txt_target = preg_replace('/\/\*([^\/]*)\*\/(\s+)/smi', '', $txt_target);
echo '<hr><pre>';
echo  $txt_target;
echo '</pre><hr>';

file_put_contents('to_check_with_a_hex_viewer.txt',$txt_target);

?>
ismith at nojunk dot motorola dot com
19 години пред
Be aware that when using the "/u" modifier, if your input text contains any bad UTF-8 code sequences, then preg_replace will return an empty string, regardless of whether there were any matches.

This is due to the PCRE library returning an error code if the string contains bad UTF-8.
sternkinder at gmail dot com
пред 18 години
From what I can see, the problem is, that if you go straight and substitute all 'A's wit 'T's you can't tell for sure which 'T's to substitute with 'A's afterwards. This can be for instance solved by simply replacing all 'A's by another character (for instance '_' or whatever you like), then replacing all 'T's by 'A's, and then replacing all '_'s (or whatever character you chose) by 'A's:

<?php
$dna = "AGTCTGCCCTAG";
echo str_replace(array("A","G","C","T","_","-"), array("_","-","G","A","T","C"), $dna); //output will be TCAGACGGGATC
?>

Although I don't know how transliteration in perl works (though I remember that is kind of similar to the UNIX command "tr") I would suggest following function for "switching" single chars:

<?php
function switch_chars($subject,$switch_table,$unused_char="_") {
    foreach ( $switch_table as $_1 => $_2 ) {
        $subject = str_replace($_1,$unused_char,$subject);
        $subject = str_replace($_2,$_1,$subject);
        $subject = str_replace($unused_char,$_2,$subject);
    }
    return $subject;
}

echo switch_chars("AGTCTGCCCTAG", array("A"=>"T","G"=>"C")); //output will be TCAGACGGGATC
?>
php-comments-REMOVE dot ME at dotancohen dot com
пред 18 години
Below is a function for converting Hebrew final characters to their
normal equivelants should they appear in the middle of a word.
The /b argument does not treat Hebrew letters as part of a word,
so I had to work around that limitation.

<?php

$text="עברית מבולגנת";

function hebrewNotWordEndSwitch ($from, $to, $text) {
   $text=
    preg_replace('/'.$from.'([א-ת])/u','$2'.$to.'$1',$text);
   return $text;
}

do {
   $text_before=$text;
   $text=hebrewNotWordEndSwitch("ך","כ",$text);
   $text=hebrewNotWordEndSwitch("ם","מ",$text);
   $text=hebrewNotWordEndSwitch("ן","נ",$text);
   $text=hebrewNotWordEndSwitch("ף","פ",$text);
   $text=hebrewNotWordEndSwitch("ץ","צ",$text);
}   while ( $text_before!=$text );

print $text; // עברית מסודרת!

?>

The do-while is necessary for multiple instances of letters, such
as "אנני" which would start off as "אןןי". Note that there's still the
problem of acronyms with gershiim but that's not a difficult one
to solve. The code is in use at http://gibberish.co.il which you can
use to translate wrongly-encoded Hebrew, transliterize, and some
other Hebrew-related functions.

To ensure that there will be no regular characters at the end of a
word, just convert all regular characters to their final forms, then
run this function. Enjoy!
мене на perochak dot com
пред 15 години
If you would like to remove a tag along with the text inside it then use the following code.

<?php
preg_replace('/(<tag>.+?)+(<\/tag>)/i', '', $string);
?>

example
<?php $string='<span class="normalprice">55 PKR</span>'; ?>

<?php
$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a null or empty string.

<?php
$string='My String <span class="normalprice">55 PKR</span>';

$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a " My String"
bublifuk на mailinator dot com
пред 7 години
A delimiter can be any ASCII non-alphanumeric, non-backslash, non-whitespace character:  !"#$%&'*+,./:;=?@^_`|~-  and  ({[<>]})
mail на johanvandemerwe dot nl
пред 6 години
Sample for replacing bracketed short-codes

The used short-codes are purely used for educational purposes for they could be shorter as in 'italic' to 'i' or 'bold' to 'b'.

Sample text
----
This sample shows how to have [italic]italic[/italic], [bold]bold[/bold] and [underline]underlined[/underline] and [strikethrough]striked[/striketrhough] text. 

with this function:

<?php
function textDecoration($html)
{
    $patterns = [
        '/\[(italic)\].*?\[\/\1\] ?/',
        '/\[(bold)\].*?\[\/\1\] ?/',
        '/\[(underline)\].*?\[\/\1\] ?/'
    ];

    $replacements = [
        '<i>$1</i>',
        '<strong>$1</strong>',
        '<u>$1</u>'
    ];

    return preg_replace($patterns, $replacements, $html);
}

$html = textDecoration($html);

echo $html; // or return
?>

results in:
----
This sample shows how to have <i>italic</i>, <b>bold</b> and <u>underlined</u> and [strikethrough]striked[/striketrhough] text.

Notice!
There is no [strikethrough]striked[/striketrhough] fallback in the patterns and replacements array
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.