note 130380 added to function.mb-substr-count
| From: | Anonymous | Date: | Sat, 21 Jun 2025 16:10:05 +0000 |
| Subject: | note 130380 added to function.mb-substr-count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-222231@lists.php.net to get a copy of this message | ||
Should I use multibyte version of substr_count php function, when my needle is space?
ChatGPT said:
When deciding whether to use the multibyte version of substr_count() (i.e., mb_substr_count()) in
PHP, even when your needle is a space character (' '), the answer depends on the encoding
of your string.
Key Considerations
1. The needle is a single-byte character (' ').
â The space character (' ') is a single-byte ASCII character, even in multibyte
encodings like UTF-8.
â So, if your string is guaranteed to be plain ASCII or the space character is what you're
counting, substr_count() will work fine even with multibyte strings.
2. The haystack may contain multibyte characters (e.g., UTF-8 text with non-ASCII characters like
ü, ñ, 漢).
â substr_count() doesn't interpret multibyte sequences correctly as characters, but it
doesn't matter for simple counting of a byte sequence like space.
â The only risk would be if the byte 0x20 (space) appears inside a multibyte sequenceâbut
in UTF-8, that doesn't happen.
Conclusion
â
Use substr_count() for counting spaces, even in multibyte strings like UTF-8.
ð Use mb_substr_count() if:
â You're working in multibyte encodings other than UTF-8.
â Your needle itself is a multibyte character (e.g., é, æ¼¢).
â You're dealing with character boundaries explicitly and want strict multibyte safety.
Example:
<?php
$str = "ä½ å¥½ ä¸ç ããã«ã¡ã¯ ì¸ê³ ìë
hello world";
$count = substr_count($str, ' '); // This will work fine for counting spaces
echo $count;
?>
In this case, substr_count() is totally safe and appropriate.
--- Can someone confirm this statement? Please upvote, if so
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 178.208.65.114)
----
Manual Page -- https://php.net/manual/en/function.mb-substr-count.php
Edit -- https://main.php.net/note/edit/130380
Del: integrated -- https://main.php.net/note/delete/130380/integrated
Del: useless -- https://main.php.net/note/delete/130380/useless
Del: bad code -- https://main.php.net/note/delete/130380/bad+code
Del: spam -- https://main.php.net/note/delete/130380/spam
Del: non-english -- https://main.php.net/note/delete/130380/non-english
Del: in docs -- https://main.php.net/note/delete/130380/in+docs
Del: other reasons-- https://main.php.net/note/delete/130380
Reject -- https://main.php.net/note/reject/130380
Search -- https://main.php.net/manage/user-notes.php