开发者

php: shortcut to writing this?

开发者 https://www.devze.com 2022-12-26 18:29 出处:网络
what would be the shortest way to write this? if(strpos($haystack, $needle)!==false){ $len = strpos($haystack, $needle)+strlen($needle);

what would be the shortest way to write this?

if(strpos($haystack, $needle)!==false){
    $len = strpos($haystack, $needle)+strlen($needle);
}else{
    $len = 开发者_StackOverflow0;
}

I remember that I saw some shortcut somewhere for this that checked and set a variable at the same time.


$len = 0;
if(($pos = strpos($haystack, $needle)) !== false) {
    $len = $pos + strlen($needle);
}

I'd recommend against the ternary ?: operator, even if it is shorter.


$len = strpos($haystack, $needle);
$len = ($len !== false) ? $len + strlen($needle) : 0;


$len=strpos($haystack, $needle);
if($len !== FALSE) {
    $len +=  strlen($needle);
}

and, in my opinion, ternary operator is terrible impact on readability.


It is called the tenary operator and can be used like this:

$len = strpos($haystack, $needle) ? strpos($haystack, $needle)+strlen($needle) : 0;

You should use it with care though, because it can make some expressions quite hard to read.


$len = strpos($haystack, $needle) ? strpos($haystack, $needle)+strlen($needle) : 0;

See also Ternary Operation.


A different approach:

$len = strlen(preg_replace('/(.*?'.preg_quote($needle,'/').')?.*/', '$1', $haystack));

Probably slower and more memory-intensive, but it does require less typing. So whether or not it's actually a shortcut depends on the definition. It does present a valid option if you're allergic to ternary operators and assignment within evaluation conditions.

You could also do

$len = preg_match('/'.preg_quote($needle,'/').'()/', $haystack, $m, PREG_OFFSET_CAPTURE)? $m[1][1] : 0

although again it's a bit wasteful of resources to be using preg_ functions to search for fixed strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号