📜  preg_replace (1)

📅  最后修改于: 2023-12-03 14:45:38.791000             🧑  作者: Mango

Preg_replace

Preg_replace is a PHP function used for string manipulation. It is used for finding and replacing patterns within a string.

Syntax
preg_replace($pattern, $replacement, $subject);
Parameters
  • $pattern: The regular expression pattern you wish to search for
  • $replacement: The replacement string for the matching pattern.
  • $subject: The input string that needs to be searched and replaced.
Return Value

It returns the modified string after replacing the matched pattern.

Example

Let's see a simple example -

$str = "Hello World. It's a beautiful day!";
$pattern = "/beautiful/";

$new_str = preg_replace($pattern, "amazing", $str);

echo $new_str;

Output:

Hello World. It's a amazing day!
Regular Expression

Preg_replace function uses regular expressions to search and replace patterns. Regular expressions are a powerful way to match patterns in text. The regular expression is a string that describes the pattern you want to match.

Examples of common regular expressions:

|Expression|Description| |:----|:----| |/^[a-z]+$/|Matches one or more lowercase letters from start to end of a string| |/\d+/|Matches one or more digits| |/hello/i|Matches the word "hello" (case insensitive)|

Conclusion

Preg_replace is a powerful PHP function used for string manipulation. It is very useful in tasks like data sanitization and URL rewriting. By using regular expressions, you can create complex patterns to match strings and replace them with new ones.