expression padawan
expression padawan

Reputation: 43

PHP, regular expression and preg_replace, need some help

I need help with little replacing:

Some text [ id ]

to...

Some text | id

I'm new in regular expression and I just don't know, how to safely keep text inside [ ]... And I don't want to use str_replace and trim... I have to use expressions (don't ask why :D )... Can somebody help me?

Upvotes: 4

Views: 86

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98901

You don't need a regex for such a simple task, str_string() will do it.

$str = str_replace(array("[","]"), array("|", ""), $str);

OUTPUT

Some text | id

Using regex to do something like this is like asking Einstein to solve 2 + 2.

Upvotes: 0

anubhava
anubhava

Reputation: 785098

This should work for non-nested square brackets:

preg_replace("/\[(.*?)\]/", "|$1", "Some text [ id ]")

OUTPUT

Some text | id

Upvotes: 5

Related Questions