PDA

View Full Version : حرفه ای: جایگزینی متن یونیکد با استفاده از preg_match



problem
چهارشنبه 09 تیر 1389, 15: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 نمی‌شود!

سوال این جاست که من چه اشتباهی می‌کنم و چه طور می‌توانم این کد را اصلاح کنم تا در تمام حالات، کلمه مورد نظر من را جایگزین کند.

problem
شنبه 12 تیر 1389, 21:40 عصر
کسی چیزی نمی‌دونه؟

rapidpich
یک شنبه 13 تیر 1389, 10:41 صبح
شاید تو unicode ت آخر با ت وسط فرق میکنه.
من تا حالا به این بر نخوردم
در ضمن شما اگه فقط میخاید فیلتر رو مثلا برداری و جا فیلترها بنویسی ****ها str_replace بهتر و سریعتره

Reza1607
دوشنبه 14 تیر 1389, 09:34 صبح
If you want to perform regular expressions on Unicode strings, the PCRE functions will NOT be of any help. You need to use the Multibyte extension : mb_ereg(), mb_eregi(), pb_ereg_replace() and so on. When doing so, be carefull to set the default text encoding to the same encoding used by the text you are searching and replacing in. You can do that with the mb_regex_encoding() function. You will probably also want to set the default encoding for the other mb_* string functions with mb_internal_encoding().

So when dealing with, say, french text, I start with these :
<?php
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
setlocale(LC_ALL, 'fr-fr');
?>
نمی دونم بدردت می خوره یا نه؟
http://ir.php.net/manual/en/ref.pcre.php