स्ट्रिंग का पहला शब्द प्राप्त करना
उदाहरण
<?php
$my_string = 'Hi there, this is a sample statement';
echo "The first word of the string is " . strtok($my_string, " ");
?>
आउटपुट
The first word of the string is Hi
व्याख्या
- strtok() - स्ट्रिंग को टोकन में विभाजित करता है। पहला कॉल स्ट्रिंग और डिलीमीटर लेता है, बाद के कॉल केवल डिलीमीटर लेते हैं।
- पहले स्पेस से पहले का भाग पहला शब्द होता है।
- strTok आंतरिक पॉइंटर रखता है, इसलिए एक ही स्ट्रिंग पर बार-बार कॉल करने पर अगले टोकन मिलते हैं।
अन्य तरीके
1. explode() के साथ
<?php
$str = 'Hi there, this is a sample statement';
$words = explode(' ', $str);
echo $words[0]; // Hi
?>
2. strstr() के साथ
<?php
$str = 'Hi there, this is a sample statement';
$first = strstr($str, ' ', true); // PHP 5.3+ - true से पहले का भाग
echo $first; // Hi
?>
3. regex के साथ
<?php
$str = 'Hi there, this is a sample statement';
preg_match('/^\S+/', $str, $matches);
echo $matches[0]; // Hi
?>
4. sscanf() के साथ
<?php
$str = 'Hi there, this is a sample statement';
sscanf($str, '%s', $first);
echo $first; // Hi
?>
तुलना
| मेथड | पक्ष | विपक्ष |
| strtok | मेमोरी कुशल, स्टेटफुल | स्ट्रिंग मोडिफाई करता है, थ्रेड-सेफ नहीं |
| explode | सरल, सरणी लौटाता है | पूरी सरणी बनाता है |
| strstr(..., true) | क्लीन, स्ट्रिंग नहीं बदलता | PHP 5.3+ आवश्यक |
| preg_match | लचीला पैटर्न | थोड़ा धीमा |