簡體   English   中英

preg_replace php正則表達式

[英]preg_replace php regex

哦,我有兩個問題。

第一。 我真的很吮吸正則表達式,它無法進入我的腦海。 任何想法或學習的想法,任何好的教程? (我已經搜索過,我找到了它們,因為它們是教程,太先進了。)

第二:

讓我們說我得到了這3個字符串:

$string = "his";

$str1 = "hi";
$str2 = "s";

所以我想做的是一個正在尋找hi並替換它的正則表達式。 但! 如果字符串中有“s”則不會被替換。 像這樣。

preg_replace('/'.$str1.'^['.$str2.']/',"replace it with this",$string);

它不起作用! (當然不是,正則表達式不是我的事!)

正如我所說的,我沒有用正則表達式得到這個。 我想找到str1,如果str2不在字符串中,它就不會被替換。 任何人?

$str = 'his';

$s1 = 'hi';
$s2 = 's';

$result = preg_replace('~' . preg_quote($s1) . '(?!' . preg_quote($s2) . ')~', 'replace with this', $str);
                      // ~hi(?!s)~
                      // this regex means:
                      //   "hi" string followed by anything but "s"

var_dump($result);

實例:

  1. http://ideone.com/XjX9n3
  2. http://ideone.com/U2JdkL

我想你想制作多個過濾器,比如: sm等等。

$s = array('s', 'm');
$result = preg_replace('~hi(?!'. join('|', $s) .')~', 'replace with this', 'him');
print $result; // him
// and
$result = preg_replace('~hi(?!'. join('|', $s) .')~', 'replace with this', 'hiz');
print $result; // replace with thisz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM