从字符串的开头和结尾删除<br>标签

How would I, given a string like this (for example), remove all break (<br>,<br />, and any other form) tags from only the beginning and end of the string?

Original string:

<br>Hello, World! https://www.youtube.com/watch?v=NU7W7qe2R0A<br><br>

Output:

Hello, World! https://www.youtube.com/watch?v=NU7W7qe2R0A

If the original string has <br> tags in the middle of the string, i.e.:

<br>Hello, World!<br><br>https://www.youtube.com/watch?v=NU7W7qe2R0A<br><br>

It should output:

Hello, World!<br><br>https://www.youtube.com/watch?v=NU7W7qe2R0A

How would I achieve this results?

You could use preg_replace and a regular expression like this.

$s = '<br><br /><Br  ><br   />Hello, World!<br><br />testing 123<br  ><BR   /><br><br />';

$stripped = preg_replace('/^(<br\s*\/?>)*|(<br\s*\/?>)*$/i', '', $s);

var_dump($stripped);

Outputs:

string(57) "Hello, World!<br><br />testing 123"

I use this :

<?
$data = '<br>Hello, World!<br><br><br /><br>';
$filter = array('<br>','<br />'); 
$data = str_replace($filter,'',$data);
var_dump($data);

To match <br> at the beginning and the end of a string use:

(?:\A<br\s*/?\s*>)+|(?:<br\s*/?\s*>)+$

$result = preg_replace('%(?:\A<br\s*/?\s*>)+|(?:<br\s*/?\s*>)+$%i', '', $text);

A more generalized regex is:

(?:\A<[a-z\d]+\s*/?\s*>)+|(?:<[a-z\d]+\s*/?\s*>)+$

$result = preg_replace('%(?:\A<[a-z\d]+\s*/?\s*>)+|(?:<[a-z\d]+\s*/?\s*>)+$%i', '', $text);

This is what I use in my projects :

Code below will handle : <br>, <br >, <br   >, <br/>, <br />, <br   />

$data = "<br><br ><br/><br />test1<br><br  ><br />test2<br><br ><br/><br />";
$str = preg_replace('/^(<br\s*?\/?>)+|(<br\s*\/?>)+$/', '', $data);
echo $str;