2017-01-11 33 views
0

我有像下面昇華正則表達式來添加isset對所有變量

$list['name'] = $obj->name; 
$list['desc'] = $obj->desc; 

等(我有超過1000線像這樣在各種功能)的代碼。

我想分配

$list['name'] = isset($obj->name)?$obj->name:''; 
$list['desc'] = isset($obj->desc)?$obj->desc:''; 

這可能使用正則表達式搜索做的,在更換之前昇華爲所有變量添加isset? 或者有沒有其他的最好的方法來做到這一點比手動?

回答

2

的東西,如這可能工作:

查找模式:

^(.*\] = {1,2})(\$obj->\w+[^;]); 

替換模式:

\1isset(\2)?\2:''; 

https://regex101.com/r/ZQbAp0/1

^ asserts position at start of a line 

1st Capturing Group (.*\] = {1,2}) 
.* matches any character (except for line terminators) 
\] matches the character ] literally (case sensitive) 
= matches the characters = literally (case sensitive) 
{1,2} Quantifier — Matches between 1 and 2 times, as many times as possible, giving back as needed (greedy) 

2nd Capturing Group (\$obj->\w+[^;]) 
\$ matches the character $ literally (case sensitive) 
obj-> matches the characters obj-> literally (case sensitive) 
\w+ matches any word character (equal to [a-zA-Z0-9_]) 
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) 
Match a single character not present in the list below [^;] 
; matches the character ; literally (case sensitive) 
+0

真棒。它正在像我想要的那樣工作。但你能再幫我一次嗎?我想搜索'$ array_name ['array_key'];'並用'isset($ array_name ['array_key'])?$ array_name ['array_key']替換它:'';'我嘗試修改正則表達式來實現並仍在嘗試。但是,如果你有答案,那將節省我很多時間。再次感謝:) – siddiq

+0

這應該是相當容易的,雖然'$ array_name'總是與'array_key'一樣的前綴嗎?所以'array'會在兩個地方匹配。基本上,這將找到模式'\ $(。+)(_ name \ [')(\ 1)(_ key'\];)'並替換'isset(\ 1)?\ 1:'';'... –

+0

我真的同意你的答案。但我的數組密鑰是動態的,而且很大。這是將xml元素解析爲數組。所以我的數組元素看起來就像'$ tag_detail ['/ product-biitem/association-ends [1]/association-end [1]/target [1]/reference-to-product-contract [1]/product-contract- key [1]/key-type-for-cbe-standard [1]/object-id [1]']'。我需要爲這種數組元素添加isset。感謝您的回答。這在一些其他情況下幫助了我。如果這是一些容易的事情,那麼這對我很有幫助。 ;):) – siddiq

1

我有一個非編程的方法來做到這一點,沒有正則表達式:

崇高的文本3具有Multiple Selections讓您編輯在同一時間多行。要使用它,只需選擇要編輯的行,然後單擊Ctrl + Shift + L

讓我們做的伎倆:您要編輯

  1. 選擇1000線。點擊Ctrl + Shift + L輸入多個選項。它看起來像:

    enter image description here

  2. 點擊End去選擇線路的末端。使用Ctrl + ArrowsCtrl + Shift來選擇$obj->name。請記住使用Ctrl + Arrows,以便您可以選擇正確的$obj->xxxxx,而不考慮字長。

  3. 點擊Ctrl + c複製它們。

  4. 轉到$obj->name的左側並輸入isset(。轉到右側並鍵入)?
  5. Ctrl + v粘貼所有副本相應的線路。
  6. 單擊End並鍵入:'';到最後。

,我們就大功告成了!這裏的結果: enter image description here