2

I'm not good in regular expression, but today I faced an unavoidable situation, So I need a regular expression that matches the case below:

|hhas.jpg||sd22-9393das.png||8jjas.png||IMG00338-20110109.jpg|

I tried this regex : /(?<=\|)(\w|\d+\.\w+)(?=\|)/i but not getting the desired results...

I want to match all the strings by using preg_match function of PHP between two | signs ie hhas.jpg, sd22-9393das.png etc...

5
  • What undesired result are you getting? Commented May 2, 2014 at 5:24
  • wHEN I TRIED THIS /(?<=\|).+(?=\|)/i ,I GET Array ( [0] => b2.png||b3.jpg||b5.jpg Commented May 2, 2014 at 5:26
  • What I need is Array ([0]=>hhas.jpg [1]=>sd22-9393das.png [2]=>8jjas.png[3]=>IMG00338-20110109.jpg Commented May 2, 2014 at 5:29
  • Please see both answers. Commented May 2, 2014 at 5:29
  • @user3041943 I would just split using preg_split() with ~\|+~. After that you only need to get rid of empty values. Commented May 2, 2014 at 8:19

4 Answers 4

2

You can use the following regex:

/\|([^|]*)\|/gi

Demo

Matched strings:

1. hhas.jpg
2. sd22-9393das.png
3. 8jjas.png
4. IMG00338-20110109.jpg
Sign up to request clarification or add additional context in comments.

Comments

2

Use this..

preg_match_all('/\|(.*?)\||/', $str, $matches);
print_r(array_filter($matches[1]));

OUTPUT :

Array
(
    [0] => hhas.jpg
    [1] => sd22-9393das.png
    [2] => 8jjas.png
    [3] => IMG00338-20110109.jpg
)

Demonstration

enter image description here

Comments

1

your expression :

/(?<=\|)(\w|\d+\.\w+)(?=\|)/i

pretty well written , but just has a few minor flaws

  • when you say \w that is only one character.

  • the OR condition

  • \d+\.\w+ will match only when it meets the same order. i.e. list of digits first followed by a . and then followed by letters or digits or underscore.

better change your regex to :

/(?<=\|)(.*?)(?=\|)/ig

this will give you anything which is between |s

also IMHO , using lookarounds for such a problem is an overkill. Better use :

/\|(.*?)\|/ig

Comments

1

Try without using regular expression.

explode('||', rtrim(ltrim ('|hhas.jpg||sd22-9393das.png||8jjas.png||IMG00338-20110109.jpg|','|'),'|'));

Output:

Array ( [0] => hhas.jpg [1] => sd22-9393das.png [2] => 8jjas.png [3] => IMG00338-20110109.jpg ) 

1 Comment

That would not suffice for the case '|a||b||c|d|e|', but I don't know if the OP needs to handle those cases aswell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.