The preg_replace () function in PHP

  • Document address
  • However, as a beginner, I was not very clever. At first, I did not understand the description of the document, so I decided to record it myself.
  • preg_replace () This function receives three parameters
parameter effect
pattern Regular expression or content to match
replacement What to replace
subject The object to be operated

  • Examples
<?php
$num = '4';
$string = "This string has four words.";
$string = preg_replace('/four/',$num, $string);
echo $string;   #This string has 4 words.
?>
  • I will no longer write about the regular expression, mainly to explain the /four/left and right sides of the above /, the experimental results are as follows
    • This part is the content to be matched. The same logo must be added at the beginning and end of the matched content, but it cannot be numbers and letters, otherwise the following error will be reported:

    PHP Warning: preg_replace(): Delimiter must not be alphanumeric or backslash in /box/main.php

    • It may or may not be /. The signs at the beginning and the end are other symbols. It is OK as long as the two are the same, such as:
    <?php
      $num = '4';
      $string = "This string has four words.";
      $string = preg_replace('@four@',$num, $string);
      echo $string; # This string has 4 words.
      ?>
    
Published 145 original articles · Like 38 · Visits 170,000+

Guess you like

Origin blog.csdn.net/yehuaner33/article/details/105301552