简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM