如何使用PHP查找字符串中的波斯语子串#محمد_حسن并保存
How to Extract the Substring
#محمد_حسن from Your PHP String Great question! There are a couple of straightforward ways to pull that specific substring out of your string in PHP—let's break them down based on your needs:
Exact Match Method
If you know the exact substring you're targeting (#محمد_حسن), using strpos() and substr() is efficient and simple:
$mystring = "this is some text.... این یک متن است. #محمد_حسن ........................"; $target_substring = "#محمد_حسن"; // Find the starting position of the target $start_pos = strpos($mystring, $target_substring); // Make sure the substring was found (strpos returns false if not) if ($start_pos !== false) { // Extract the substring using its known length $extracted = substr($mystring, $start_pos, strlen($target_substring)); // Now $extracted holds "#محمد_حسن" var_dump($extracted); // For testing } else { echo "The target substring wasn't found in the string."; }
Flexible Hashtag Matching
If you might need to extract similar hashtags later (not just this exact one), a regex with preg_match() is better—especially since we're dealing with Unicode (Persian) characters:
$mystring = "this is some text.... این یک متن است. #محمد_حسن ........................"; // Regex pattern to match hashtags starting with #, followed by Persian chars/underscores // The 'u' modifier ensures proper Unicode handling if (preg_match('/#[\p{Persian}_]+/u', $mystring, $matches)) { $extracted_hashtag = $matches[0]; // $extracted_hashtag now contains "#محمد_حسن" var_dump($extracted_hashtag); // For testing } else { echo "No matching hashtag found."; }
Key Notes:
- Always check if
strpos()returns!== false—it can return0if the substring is at the start of the string, which is a valid position (not an error). - The
umodifier in the regex is critical for correctly parsing Persian Unicode characters in PHP.
内容的提问来源于stack exchange,提问作者efns
相关产品推荐
相关产品推荐

