problem
چهارشنبه 09 تیر 1389, 16:55 عصر
تا به حال برای من پیش نیومده بود که متن یونیکد رو با استفاده از preg_match جایگزین کنم و حالا که پیش اومده کاملاً گیج شدم.
به کد زیر نگاه کنید:
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
// Case 1
$out = preg_replace("#(\b|^)فیلتر(\b|$)#i", "\\1".'*****'."\\2", " فیلتر \r\n فیلتر \r\n فیلترها \r\n فیلتر.ها \r\n");
echo nl2br($out);
// Case 2
$out = preg_replace("#(\b|^)تست(\b|$)#i", "\\1".'*****'."\\2", " تست \r\n تست \r\n تستها \r\n تست.ها \r\n");
echo nl2br($out);
// Case 3
$out = preg_replace("#^تست$#i", "\\1".'*****'."\\2", " تست \r\n تست \r\n تستها \r\n تست.ها \r\n");
echo nl2br($out);
?>
</body>
</html>
اگر کد را اجرا کنید میبینید که در حالت اول، فقط عبارت «فیلترها» به «*****ها» تبدیل میشود و عبارات دیگر اصلا match نمیشوند. به طرز جالبی، در حالت دوم و در مورد واژه تست قضیه برعکس است و فقط در «تستها» match نمیشود و در بقیه حالاتش تابع عمل میکند.
در حالت سوم هم از b\ برای تعیین حدود کلمه استفاده نکردم و فقط ^ و $ را به کار بردم که در این حالت اصلاً متن فارسی match نمیشود!
سوال این جاست که من چه اشتباهی میکنم و چه طور میتوانم این کد را اصلاح کنم تا در تمام حالات، کلمه مورد نظر من را جایگزین کند.
به کد زیر نگاه کنید:
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
// Case 1
$out = preg_replace("#(\b|^)فیلتر(\b|$)#i", "\\1".'*****'."\\2", " فیلتر \r\n فیلتر \r\n فیلترها \r\n فیلتر.ها \r\n");
echo nl2br($out);
// Case 2
$out = preg_replace("#(\b|^)تست(\b|$)#i", "\\1".'*****'."\\2", " تست \r\n تست \r\n تستها \r\n تست.ها \r\n");
echo nl2br($out);
// Case 3
$out = preg_replace("#^تست$#i", "\\1".'*****'."\\2", " تست \r\n تست \r\n تستها \r\n تست.ها \r\n");
echo nl2br($out);
?>
</body>
</html>
اگر کد را اجرا کنید میبینید که در حالت اول، فقط عبارت «فیلترها» به «*****ها» تبدیل میشود و عبارات دیگر اصلا match نمیشوند. به طرز جالبی، در حالت دوم و در مورد واژه تست قضیه برعکس است و فقط در «تستها» match نمیشود و در بقیه حالاتش تابع عمل میکند.
در حالت سوم هم از b\ برای تعیین حدود کلمه استفاده نکردم و فقط ^ و $ را به کار بردم که در این حالت اصلاً متن فارسی match نمیشود!
سوال این جاست که من چه اشتباهی میکنم و چه طور میتوانم این کد را اصلاح کنم تا در تمام حالات، کلمه مورد نظر من را جایگزین کند.