note 130380 added to function.mb-substr-count

From: 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

« previous php.notes (#222231) next »