0

I have a string like this:

$imgs = "uploads/images/adsense.png|uploads/images/tree-7835_960_720.jpg|uploads/images/way-427984_960_720.jpg|uploads/images/friendship-1081843_960_720.jpg|uploads/images/pinky-swear-329329_960_720.jpg"

I want only the part that refers to the first image:

uploads/imagens/adsense.png

How can I use regex to filter for the content before the first |?

$image = preg_replace(/(*)(\/*)/, $1 ,$imgs)
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Gisele
  • 65
  • 7

5 Answers5

3

Why use regex? You could just do:

substr($imgs, 0, strpos($imgs, '|'));
Eihwaz
  • 1,234
  • 10
  • 14
  • Thank´s @Eihwaz your code works well, I only chose the NathanielFord response because it is simpler – Gisele Mar 23 '16 at 19:18
  • @Gisele We're here to help each other, the important thing is that you've found what you were looking for :) – Eihwaz Mar 23 '16 at 19:22
2

When you have an input value like this:

$imgs = "uploads/images/adsense.png|uploads/images/tree-7835_960_720.jpg|uploads/images/way-427984_960_720.jpg|uploads/images/friendship-1081843_960_720.jpg|uploads/images/pinky-swear-329329_960_720.jpg"

You simply need to explode it, using | as the delimiter:

$images = explode("|", $imgs);

The image you want is the first one:

$images[0];

While you can use regex, there is no particular reason to in this case, and it risks obfuscating what you're doing.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
1
/^([^|]*)/

This matches any number of characters from the beginning of the string to the first | character.

Mark Evaul
  • 653
  • 5
  • 11
0

Since you added regex tag.

You can use the positive lookahead like below, along with ^ anchor.

Regex: ^.*?(?=\|)

Regex101 Demo

  • I know lookaround assertions are a little inefficient. But it's also a valid solution. Care to explain down vote ? –  Mar 23 '16 at 19:09
0

use

$upload = explode('|', $imgs);
echo $upload[0];

hope it helps :)

FastTurtle
  • 1,747
  • 11
  • 15