Using preg replace in php

preg_replace

Searches subject for matches to pattern and replaces them with replacement .

To match an exact string, rather than a pattern, consider using str_replace() or str_ireplace() instead of this function.

Parameters

The pattern to search for. It can be either a string or an array with strings.

Several PCRE modifiers are also available.

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns 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 fewer elements in the replacement array than in the pattern array, any extra pattern s will be replaced by an empty string.

replacement may contain references of the form \ n or $ 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. Note that backslashes in string literals may require to be escaped.

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 . This creates an isolated $1 backreference, leaving the 1 as a literal.

When using the deprecated e modifier, this function escapes some characters (namely ‘ , » , \ and NULL) in the strings that replace the backreferences. This is done to ensure that no syntax errors arise from backreference usage with either single or double quotes (e.g. ‘strlen(\’$1\’)+strlen(«$2»)’ ). Make sure you are aware of PHP’s string syntax to know exactly how the interpreted string will look.

The string or an array with strings to search and replace.

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.

If the subject array is associative, keys will be preserved in the returned value.

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

Читайте также:  Java constant http code

If specified, this variable will be filled with the number of replacements done.

Return Values

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 or null if an error occurred.

Errors/Exceptions

Using the «\e» modifier is an error; an E_WARNING is emitted in this case.

If the regex pattern passed does not compile to a valid regex, an E_WARNING is emitted.

Examples

Example #1 Using backreferences followed by numeric literals

$string = ‘April 15, 2003’ ;
$pattern = ‘/(\w+) (\d+), (\d+)/i’ ;
$replacement = ‘$1,$3’ ;
echo preg_replace ( $pattern , $replacement , $string );
?>

The above example will output:

Example #2 Using indexed arrays with preg_replace()

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

The above example will output:

The bear black slow jumps over the lazy dog.

By ksorting patterns and replacements, we should get what we wanted.

ksort ( $patterns );
ksort ( $replacements );
echo preg_replace ( $patterns , $replacements , $string );
?>

The above example will output:

The slow black bear jumps over the lazy dog.

Example #3 Replacing several values

The above example will output:

Example #4 Strip whitespace

This example strips excess whitespace from a string.

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

Example #5 Using the count parameter

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

The above example will output:

Notes

Note:

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() .

Note:

When both pattern and replacement are arrays, matching rules will operate sequentially. That is, the second pattern / replacement pair will operate on the string that results from the first pattern / replacement pair, not the original string. If you want to simulate replacements operating in parallel, such as swapping two values, replace one pattern by an intermediary placeholder, then in a later pair replace that intermediary placeholder with the desired replacement.

$p = array( ‘/a/’ , ‘/b/’ , ‘/c/’ );
$r = array( ‘b’ , ‘c’ , ‘d’ );
print_r ( preg_replace ( $p , $r , ‘a’ ));
// prints d
?>

See Also

  • PCRE Patterns
  • preg_quote() — Quote regular expression characters
  • preg_filter() — Perform a regular expression search and replace
  • preg_match() — Perform a regular expression match
  • preg_replace_callback() — Perform a regular expression search and replace using a callback
  • preg_split() — Split string by a regular expression
  • preg_last_error() — Returns the error code of the last PCRE regex execution
  • str_replace() — Replace all occurrences of the search string with the replacement string
Читайте также:  Java reflection get protected methods

User Contributed Notes 9 notes

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
Match exactly n times
Match at least n times
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)

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:

function expandCamelCase ( $source ) return preg_replace ( ‘/(?>
?>

Before:
ExpandCamelCaseAPIDescriptorPHP5_3_4Version3_21Beta
After:
Expand Camel Case API Descriptor PHP 5_3_4 Version 3_21 Beta

If you would like to remove a tag along with the text inside it then use the following code.

$string = preg_replace ( ‘/(.+?)+()/i’ , » , $string );
?>

This will results a » My String»

How to replace all comments inside code without remove crln = \r\n or cr \r each line?

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 ‘


' ;
echo $txt_target ;
echo '

‘ ;

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

// /* comment */
$txt_target = preg_replace ( ‘/\/\*([^\/]*)\*\/(\s+)/smi’ , » , $txt_target );
echo ‘


' ;
echo $txt_target ;
echo '

‘ ;

file_put_contents ( ‘to_check_with_a_hex_viewer.txt’ , $txt_target );

Читайте также:  Intellij idea kotlin gradle project

Источник

PHP preg_replace

Summary: in this tutorial, you’ll learn how to use the PHP preg_replace() function to search and replace using regular expressions.

Introduction to the PHP preg_replace() function

The preg_replace() function searches for matches and replaces them with a pattern.

The following shows how to use the preg_replace() function with a single string:

preg_replace( string $pattern, string $replacement, string $subject, int $limit = -1, int &$count = null ): stringCode language: PHP (php)

The preg_replace() function has the following parameters:

  • $pattern is a regular expression to match.
  • $replacement is a string to replace. It may contain the backreferences.
  • $subject is a string to search and replace.
  • $limit is the maximum possible replacement for the pattern. By default, it is -1, which is unlimited.
  • $count stores the number of replacements.

If the $subject matches the $pattern, the preg_replace() function replaces the match with the $replacement and returns it.

PHP preg_replace() function examples

Let’s take some examples of using the preg_replace() function.

1) Using the PHP preg_replace() function to change the date format

The following example uses the preg_replace() function to change the date string from dd-mm-yyyy to mm-dd-yyyy format:

 $pattern = '/(\d)-(\d)-(\d)/'; $replacement = '\2-\1-\3'; $str = '25-12-2021'; echo preg_replace($pattern, $replacement, $str);Code language: PHP (php)
12-25-2021Code language: PHP (php)

The following regular expression matches the date in the dd-mm-yyyy format:

/(\d2>)-(\d2>)-(\d4>)/Code language: PHP (php)

It consists of three capturing groups for day (\d) , month (\d) , and year (\d) .

The replacement string contains three backreferences \2 for the second capturing group which is month, \1 for the first capturing group which is day, and \3 for the third capturing group which is the year.

Therefore, the preg_replace() changes the format of the date from dd-mm-yyyy to mm-dd-yyyy .

2) Using the PHP preg_replace() function to remove the excessive whitespace

The following example uses the preg_replace() function to strip excess whitespace from a string:

 $str = 'PHP is awesome'; echo preg_replace('/\s\s+/', ' ', $str);Code language: PHP (php)
PHP is awesomeCode language: PHP (php)

The pattern /\s\s+/ matches one or more spaces.

PHP preg_replace() function with arrays

The preg_replace() function also accepts the $pattern , $replacement , and $subject as arrays:

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

If both $pattern and $replacement are arrays and $subject is a string, the preg_replace() function will replace each pattern in the $pattern array with the replacement in the $replacement array.

If the $replacement array has fewer elements than the $pattern array, the preg_replace() function wil replace extra patterns with an empty string.

If the $subject is an array, the preg_replace() function searches and replaces each string in the array and returns the result as an array.

Summary

Источник

Оцените статью