Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text before and after nth occurrence of hyphen

Tags:

php

Question:

ABC-101-Description-text-1
ABC-2001-Description-text-with-more-text-2
ABC-20001-Some-more-Description-text-with-more-text-3

Could someone help me get all the text before the nth occurrence of the hyphen, so if I wanted ABC-20001 in one instance OR wanted everything after ABC-2001.

I understand that I need to use strstr or strpos but am unsure, would appreciate some assistance...

like image 217
devofash Avatar asked Dec 31 '12 11:12

devofash


1 Answers

If you already know 'n' below as an integer:

$parts = explode('-',$string,$n);

Let's take this string:

$string = "ABC-20001-Some-more-Description-text-with-more-text-3";

If you want what's before the 2nd hyphen:

$parts = explode('-',$string,$n+1); // n=2,
$parts[0] = 'ABC-20001';
$parts[1] = 'Some-more-Description-text-with-more-text-3';

Third example here: http://uk1.php.net/manual/en/function.explode.php.

like image 91
MyStream Avatar answered Oct 08 '22 14:10

MyStream