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
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
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]
...
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
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"
// }