我们如何在php中选择一个特定字符的字符串? 注意:不使用explode()

How we can select a string up to specific character in php?

ie I have a string Wednesday 16-January-2013. I need to get only up to first space.

ie output should be Wednesday.

I done it using explode,

<?php
explode(" ",Wednesday 16-January-2013)
?>

But too many explodes and array are permitted in the code. So,

How I can do it without using explode()?

As of PHP 5.3.0 you can use strstr function to return the part of the haystack before the first occurrence of the needle (excluding the needle):

$dayOfWeek = strstr('Wednesday 16-January-2013', ' ', true);
echo $dayOfWeek; // prints Wednesday

You can do this by using the substr method:

substr ( string $string , int $start [, int $length ] )

You could use it in combination with strpos like this:

$spacelocation = strpos($originalstring, " ");

if ($spacelocation !== false) {
    $day = substr($originalstring, 0, $spacelocation);
}

You can simply use strstr():

strstr('Wednesday 16-January-2013', ' ', true);

The third argument $before_needle makes the function return only the part before the space.

See also: strstr()

Before PHP 5.3 (or if you need to need to branch based on the existence of the space) you would write it like this:

$s = 'Wednesday 16-January-2013';
if (($p = strpos($s, ' ')) !== false) {
    echo substr($s, 0, $p);
} else {
    // space wasn't found, bad, bad.
}

If the space is found at the start of the string, it could be considered an error too; in that case, the condition is simply if ($p = strpos($s, ' ')) { (i.e. it exists and does not appear at the beginning)

An example:

$str = "Wednesday 16-January-2013";
$out = substr( $str, 0, strpos( $str, " " ));