Shoxa
Shoxa

Reputation: 19

How get string before symbol

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

Upvotes: 0

Views: 69

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

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

Upvotes: 1

Related Questions