You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 return 0 if the substring is at the start of the string, which is a valid position (not an error).
  • The u modifier in the regex is critical for correctly parsing Persian Unicode characters in PHP.

内容的提问来源于stack exchange,提问作者efns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:29:23