1

So let's say that I have the following code:

$var = '-77-randomtext-moretext.extension'

So that nothing in the variable is fixed, except for the hyphens ( - ), and the extension.

Then let's say that I need to strore the '-77-' part as a string. '-77-' meaning anything in between the first two hyphens, including the hyphens themselves.

How could I do this?

  • http://stackoverflow.com/questions/1715854/how-to-return-a-regex-match-in-php-instead-of-replacing – Joseph Mar 08 '12 at 19:18
  • 1
    @Joseph - ["Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems."](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Lix Mar 08 '12 at 19:20
  • @Lix - [And some people, when confronted with regular expressions, think "I know, I'll use a catchy quote that I remember". Now they have added nothing to the discussion.](http://stackoverflow.com/questions/1098296/are-regular-expressions-worth-the-hassle) – mario Mar 08 '12 at 21:09

5 Answers5

3

The two primary ways to do that would be either explode or preg_filter.

Split:

$varArray = explode( '-', $var );
$string77 = '-' . $varArray[1] . '-'; // equals '-77-'

preg_filter;

$string77 = preg_filter( '/^(-.+-).*$/', '$1', $varArray ); // equals '-77-', or NULL if the string doesn't match

The split method is quicker, but less reliable. preg_filter will ensure you always get either the data you want, or a NULL if it doesn't exist, but requires more processing.

kitti
  • 14,663
  • 31
  • 49
  • Ended up using the explode one. Thanks so much, this was really a difficult task for me. –  Mar 08 '12 at 19:39
1

You could use:

$parts = explode('-', $var);
$txt = '-' . $parts[1] . '-';
Config
  • 1,672
  • 12
  • 12
1

Use the distance between two strpos() calls and get the substr() based on those positions:

$var = '-77-randomtext-moretext.extension';
$first_pos = strpos($var,'-');

$second_pos = strpos($var,'-',($first_pos+1)); //we offset so we find the second 
$length = ($second_pos+1) - $first_pos; //get the length of the string between these points
echo  substr($var,$first_pos,$length); 

You could also use a regex expression (preg_match()) or use the explode() approach:

$pieces = explode('-',$var);
$results = '-'.$pieces[0].'-';

But this only works if you know that the first and second delimiter will be the same.

Ben D
  • 14,321
  • 3
  • 45
  • 59
1

You could use a regular expression: /-(.+?)-/

rcurts
  • 45
  • 9
1
$var = '-77-randomtext-moretext.extension';
preg_match('/-(.+?)-/', $var, $matches);
echo $matches[0]; // -77-
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • The first index of the array returned by `preg_match` is the entire matching string, not the first matched group. – kitti Mar 08 '12 at 19:24
  • 1
    @RyanP: You should try above code out or should I create a demo for you on codepad ? – Sarfraz Mar 08 '12 at 19:26