socrates socrates - 4 months ago 40
PHP Question

Stripping two characters from a string PHP using regular expression

I have a list of html tags of the form


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


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


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/

The Solution

So, your code could be:

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

Here's a demo, showing how it works.