Tags
PHP , substr
Asked 3 years ago
9 Jun 2021
Views 371
pratik

pratik posted

how to use PHP substr() and strip_tags() ?

how to use PHP substr() and strip_tags() ?
jaydeep

jaydeep
answered Feb 28 '23 00:00

The substr() and strip_tags() functions are both useful functions in PHP for manipulating strings . Here's a brief overview of how to use these functions:

substr()
The substr() function is used to extract a portion of a string . It takes two or three parameters:


substr(string $string, int $start, int|null $length = null): string

$string is the input string to extract a portion from.

$start is the position in the string to start extraction from.

$length (optional) is the length of the substring to extract. If not provided, the function will extract all the remaining characters from the start position.
Here's an example:


$string = "Hello, world!";
$substring = substr($string, 0, 5); // "Hello"


In this example, we extract the first 5 characters from the string using substr().

strip_tags()
The strip_tags() function is used to remove HTML and PHP tags from a string. It takes one or two parameters:



strip_tags(string $string, string|null $allowable_tags = null): string

$string is the input string to remove tags from.
$allowable_tags (optional) is a string of tags to allow in the output. Any other tags will be removed. If not provided, all tags will be removed.
Here's an example:



$string = "<p>Hello, <b>world</b>!</p>";
$stripped = strip_tags($string); // "Hello, world!"

In this example, we remove all HTML tags from the string using strip_tags() . If we wanted to allow the <b> tag, we could call the function like this:



$string = "<p>Hello, <b>world</b>!</p>";
$stripped = strip_tags($string, "<b>"); // "Hello, <b>world</b>!" 

In this case, the <b> tag is allowed and is not removed from the string. All other tags are removed.
Post Answer