دالة PHP substr_count ()
مثال
احسب عدد مرات ظهور "العالم" في السلسلة:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
تحسب الدالة substr_count () عدد المرات التي تحدث فيها سلسلة فرعية في سلسلة.
ملاحظة: السلسلة الفرعية حساسة لحالة الأحرف.
ملاحظة: لا تحسب هذه الوظيفة السلاسل الفرعية المتداخلة (انظر المثال 2).
ملاحظة: تقوم هذه الوظيفة بإنشاء تحذير إذا كانت معلمة البدء بالإضافة إلى معلمة الطول أكبر من طول السلسلة (انظر المثال 3).
بناء الجملة
substr_count(string,substring,start,length)
قيمه المعامل
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
substring | Required. Specifies the string to search for |
start | Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string |
length | Optional. Specifies the length of the search |
تفاصيل تقنية
قيمة الإرجاع: | تُرجع عدد مرات حدوث السلسلة الفرعية في السلسلة |
---|---|
إصدار PHP: | 4+ |
التغيير: | PHP 7.1 - يمكن أن تكون معلمات الطول 0 أو رقمًا سالبًا. PHP 7.1 - يمكن أن تكون معلمات البدء رقمًا سالبًا. PHP 5.1 - تمت إضافة معلمات البدء والطول . |
مزيد من الأمثلة
مثال
باستخدام جميع المعلمات:
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
مثال
سلاسل فرعية متداخلة:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
مثال
إذا تجاوزت معلمات البدء والطول طول السلسلة ، فستصدر هذه الوظيفة تحذيرًا:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
سينتج عن هذا تحذير لأن قيمة الطول تتجاوز طول السلسلة (3 + 9 أكبر من 12)
❮ مرجع سلسلة PHP