Take the 2-minute tour ×

i'm trying to learn a bit about regex, can anyone explain to me what is going on here? And give example on a regex that would provide the expected output? Thanks!

input data = 'Sometext|even more text'

regex = '(.*)?\|?.*'

replacement = '$1'

expected output = 'Sometext'

actual output = 'Sometext|even more text'


preg_filter("(.*)?\|?.*", "$1", 'Sometext|even more text'); // returns  Sometext|even more text
share|improve this question
Please add you PHP code as well. –  hakre Apr 11 '12 at 14:08
\|? also makes the vertical bar optional. –  nickb Apr 11 '12 at 14:11

4 Answers 4

up vote 1 down vote accepted

(.*) is greedy, so matches everything. $1 is everything then.

You are probably looking for:

share|improve this answer
And what would a non greedy (.*) look like? –  netbrain Apr 11 '12 at 14:11
@netbrain: (.*?) but it's better to avoid the match-all operator and instead exclude characters you don't want to match, like @hakre did. –  Felix Kling Apr 11 '12 at 14:12
You make it non-greedy by adding a ?. However, I edited the answer because you don't want to understand but just to have code ;) –  hakre Apr 11 '12 at 14:12
I'd like to know exactly what this [^|] does? matches everything up until |? –  netbrain Apr 11 '12 at 14:19

Your regex is saying "all chars, followed by an optional |, followed by 0 or more chars".

Change the initial (.*) to ([^\|]*), or make the | non-optional.

share|improve this answer

* is greedy, which means it will try to match as much text as possible. In this case:

  • (.*)? will match all the text
  • \|?.* will match the "rest" (empty string)

try: regex = '\|[^|]*', replacement = ''

share|improve this answer

If you change your regex to (\w+)?\|?.*, specifically adding the + after the \w then you will get your expected answer of 'Sometext'.

The reason you were having the whole string match is that the first .* was matching the whole string. With the changes I have above, you will be matching on any word character.

share|improve this answer

Your Answer


