0

I have strings

TEST #1 - Description
TEST #2 / Description
...

I need get string before # but with #1, output: TEST #1

strstr($str, '#', true);

These code output: TEST i need TEST #1

Shoxa
  • 19
  • 4
  • I think it is posible with preg_match but i dont know how make. – Shoxa Jan 22 '18 at 21:26
  • you could just explode on space. –  Jan 22 '18 at 21:33
  • @rtfm: Yes, however I anticipated the _"but sometimes there is no space"_ or _"doesn't work for `TEST-#1`"_. – AbraCadaver Jan 22 '18 at 21:37
  • @Shoxa please explain the variability of your input data, so that we can provide an accurate method without "guessing" what your strings look like. Can we possibly use `^[^-/]+(?= )`? – mickmackusa Jan 22 '18 at 21:40
  • you may assume what you like, ill base any answer on the actual code provided @AbraCadaver –  Jan 22 '18 at 21:40
  • or `^\D+\d+` ? It is best to give us realistic sample input data. – mickmackusa Jan 22 '18 at 21:47
  • @Shoxa If you are satisfied with AbraCadaver's answer please mark it with the green tick. If you would like to receive more answers/support, please improve your question by addressing the comments/concerns under your question. – mickmackusa Jan 25 '18 at 01:18

1 Answers1

1

If the format is consistent (word space # digits) then:

$parts  = explode(' ', $str);
$result = $parts[0] . ' ' . $parts[1];

I assume the number can be multiple digits, so you'll need regex:

preg_match('/[^#]+#\d+/', $str, $match);
echo $match[0];

If you need multiple from one string then:

preg_match_all('/[^#]+#\d+/', $str, $matches);
print_r($matches[0]);

Either way you are matching:

  • [^#]+ one or more + NOT ^ # characters
  • Followed by # character
  • Followed by one or more + digits \d
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87