स्ट्रिंग के अंतिम शब्द की लंबाई
उदाहरण
<?php
function last_word_len($my_string) {
$position = strrpos($my_string, ' ');
if (!$position) {
$position = 0;
} else {
$position = $position + 1;
}
$last_word = substr($my_string, $position);
return strlen($last_word);
}
print_r("The length of the last word is ");
print_r(last_word_len('Hey') . "\n");
print_r("The length of the last word is ");
print_r(last_word_len('this is a sample') . "\n");
?>
आउटपुट
The length of the last word is 3 The length of the last word is 6
कोड व्याख्या
- strrpos() - स्ट्रिंग में अंतिम स्पेस की स्थिति ढूंढता है।
- कोई स्पेस नहीं: यदि $position false है (स्पेस नहीं मिला), तो $position = 0 (पूरा स्ट्रिंग एक शब्द)।
- स्पेस मिला: $position + 1 से अंतिम शब्द शुरू होता है।
- substr() - उस स्थिति से अंत तक सबस्ट्रिंग निकालता है।
- strlen() - अंतिम शब्द की लंबाई लौटाता है।
एज केस हैंडलिंग
मूल कोड में ट्रेलिंग स्पेसेस हैंडल नहीं होते:
<?php
function last_word_len_robust($str) {
$str = rtrim($str); // ट्रेलिंग स्पेसेस हटाएं
if ($str === '') return 0;
$pos = strrpos($str, ' ');
if ($pos === false) {
return strlen($str); // कोई स्पेस नहीं - पूरा स्ट्रिंग
}
return strlen($str) - $pos - 1;
}
// टेस्ट
echo last_word_len_robust("Hello World ") . "\n"; // 5 (World)
echo last_word_len_robust("Single") . "\n"; // 6
echo last_word_len_robust("") . "\n"; // 0
?>
बिल्ट-इन विकल्प
<?php
$str = "this is a sample";
// explode से शब्दों में विभाजित
$words = explode(' ', trim($str));
$last = end($words);
echo strlen($last); // 6
// या regex के साथ
preg_match('/\S+$/', $str, $matches);
echo strlen($matches[0]); // 6
?>