js

Sunday, January 28, 2024

Explain preg_replace() in php

 

In PHP, the preg_replace() function is used for performing regular expression-based search and replace operations on strings. It allows you to search for a specified pattern (defined using a regular expression) within a string and replace occurrences of that pattern with another string.

Here's an explanation of preg_replace():

Syntax:

php
preg_replace(pattern, replacement, subject, limit = -1, &count);
  • pattern: The regular expression pattern to search for.
  • replacement: The string to replace the matched patterns with.
  • subject: The input string or an array of input strings.
  • limit (optional): The maximum number of replacements to perform. By default, it's set to -1, which means no limit.
  • count (optional): If provided, this variable will be filled with the number of replacements performed.

Return Value:

preg_replace() returns the modified string or an array of modified strings.

Example:

php
<?php
// Example using preg_replace()
$inputString
= "This is a sample string with extra spaces.";
// Remove multiple spaces with a single space

$trimmedString
= preg_replace('/\s+/', ' ', $inputString);
// Display the results

echo "<pre>";
echo "Original String: $inputString\n";
echo "Trimmed String: $trimmedString\n";
?>

In this example:

  • The regular expression '/\s+/' is used to match one or more whitespace characters (spaces, tabs, newlines).
  • The replacement string is ' ', which means a single space.
  • The preg_replace() function replaces sequences of one or more whitespace characters with a single space.

Output:

php
Original String: This is a sample string with extra spaces.
Trimmed String: This is a sample string with extra spaces.

This is a simple example, but preg_replace() becomes more powerful when working with more complex regular expressions. It's commonly used for tasks such as pattern-based substitutions and manipulations in strings.

No comments:

Post a Comment

SEBA Class X Science অধ্যায়-১৬ প্রাকৃতিক সম্পদৰ ব্যৱস্থাপনা Questions and Answers

  অধ্যায়-১৬ প্রাকৃতিক সম্পদৰ ব্যৱস্থাপনা নির্বাচিত প্রশ্নোত্তৰ প্রশ্নঃ বৃহৎ নদীবান্ধ নিৰ্মাণৰ লগত জড়িত থকা সমস্যা এটা উল্লেখ কৰা। HSL...