توابع رشته PHP

رشته‌ها توالی کاراکترها هستند، مانند "Hello world!".

توابع رشته PHP

در این بخش، ما توابع عملیات رشته‌ای رایج را یاد خواهیم گرفت.

PHP strlen() تابع

strlen() تابع طول یک رشته را به تعداد کاراکتر برمی‌گرداند.

مثال زیر طول رشته "Hello world!" را برمی‌گرداند:

Example

<?php
echo strlen("Hello world!");
?>

Run Instance

خروجی کد بالا: 12

Tip:strlen() به طور رایج در حلقه‌ها و دیگر توابع استفاده می‌شود، و در زمانی که باید به پایان یک رشته رسید، بسیار مهم است. (مثلاً در یک حلقه، ممکن است بخواهیم که در پس از آخرین کاراکتر رشته، حلقه را متوقف کنیم).

شمارش کلمات در یک رشته

PHP str_word_count() تابع برای شمارش کلمات در یک رشته است:

Example

<?php
echo str_word_count("Hello world!"); // خروجی 2
?>

Run Instance

The output of the above code is:

2

Reverse the String

PHP strrev() Function Reverses the String:

Example

<?php
echo strrev("Hello world!"); // Output !dlrow olleH
?>

Run Instance

The output of the above code is:

!dlrow olleH

PHP strpos() Function

The strpos() function is used to search for a specified character or text within a string.

If a match is found, it will return the position of the first matching character. If no match is found, it will return FALSE.

The following example retrieves the text "world" from the string "Hello world!":

Example

<?php
echo strpos("Hello world!","world");
?>

Run Instance

The output of the above code is: 6.

Tip:In the above example, the position of the string "world" is 6. The reason it is 6 (not 7) is that the position of the first character in the string is 0, not 1.

Replace text in the string

The PHP str_replace() function replaces some strings with other strings in the string.

The following example replaces the text "world" with "Kitty":

Example

<?php
echo str_replace("world", "Kitty", "Hello world!"); // Output Hello Kitty!
?>

Run Instance

The output of the above code is:

Hello Kitty!

Complete PHP String Reference Manual

For a complete reference manual of string functions, please visit our PHP String Reference Manual.

This manual provides a brief description and example of each function!