socrates socrates - 2 months ago 11
PHP Question

Stripping two characters from a string PHP using regular expression

I have a list of html tags of the form

<a>
<div>
...


How would I strip the
<>
away from the strings to return the word in between using regular expressions?

Attempts:

preg_replace('~<>~', ' ', $tag);, preg_replace("[<>]", ' ', $tag);, and preg_replace(array(">","<"), " ", $tag);

Answer

The Problem

Based on your examples, the problem is that you are not using delimiters. You must use a delimiter (typically /, but often ~). From the manual:

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

The Solution

So, your code could be:

$newString = preg_replace("/[<>]/", ' ', $tag);

Here's a demo, showing how it works.

Comments