tags:

views:

48

answers:

4

How can I check in PHP whether a string contains '-'?

Example

ABC-cde::abcdef

if '-' is found then I have to perform split() to split ABC from cde::abcdef

else no need to perform split()

like cde::abcdef

+2  A: 

if (strpos($string, "-") !== false) { split(); }

Select0r
This code will not work in PHP 5.3. Deprecated error. Now it is a preg_split();
Alexander.Plutov
Source? This doesn't mention that strpos is deprecated: http://php.net/manual/en/function.strpos.php
Select0r
I think Alexander is refering to split()
Gordon
It's [split](http://uk3.php.net/manual/en/function.split.php) that has been deprecated, not [strpos](http://php.net/manual/en/function.strpos.php). Where regular expressions are not required, [explode](http://uk3.php.net/manual/en/function.explode.php) is recommended instead.
Mike
A: 

Just split() it and count the elements in the return array. Maybe it's even enough to continue with the first (or last) element, e.g. $newstring = split($oldstring, '-')[0]...

Martin
Oops. As @Web Developer I meant explode, too. Sorry.
Martin
+3  A: 

Just use explode that should be sufficient

eg. explode ('-',$urstring);

This will only split it (into an array of strings) if "-" exist else return the entire string as a array

Web Developer
+1  A: 

How about just using the $limit parameter of explode()?

This will return an array in both your examples, with only one element in the latter case.

Note that split() is deprecated as of PHP 5.3: http://php.net/manual/en/function.split.php

$s1 = 'ABC-cde::abcdef';
$s2 = 'cde::abcdef';
$s3 = 'ABC-with-more-hyphens';

explode('-', $s1, 2);
// array(2) {
//   [0]=>
//   string(3) "ABC"
//   [1]=>
//   string(11) "cde::abcdef"
// }

explode('-', $s2, 2);
// array(1) {
//   [0]=>
//   string(11) "cde::abcdef"
// }

explode('-', $s3, 2);
// array(2) {
//   [0]=>
//   string(3) "ABC"
//   [1]=>
//   string(17) "with-more-hyphens"
// }
Paul Annesley