2016-01-16 37 views
-3

好,我找到了答案之間的每一個空格字符 PHP - split a string of HTML attributes into an indexed array更換報價

感謝的

我想和%20

實例替換引號之間的每一個空格字符:

<input type="text" title="this is a fish"> 

預期結果:

<input type="text" title="this%20is%20a%20fish"> 

又如

$_POST['foo'] = '<input type="text" title="this is a fish">'; 
$parsed = '<input type="text" title="this%20is%20a%20fish">'; 

正如所看到的,我只whant到qoutes內更換空間,而不是任何其他。 所以str_replace根本不會在這裏幫助

這樣做的desierd最終的結果是參數數組

這是我做過什麼

<?php 
$tag_parsed = trim($tag_parsed); 
$tag_parsed = str_replace('"', '', $tag_parsed); 
$tag_parsed = str_replace(' ', '&', $tag_parsed); 
parse_str($tag_parsed, $tag_parsed); 

但是,當一個參數中有空格,它打破。

+0

輸出 - >富Ø – varunkumar

+0

@DenisAlexandrov是不是我問,我有這樣的例子一個字符串,我不想每天更換空白,只是那些在qoutes –

+0

@MordiSacks但是,功能是一樣的。你只需要正確使用它們。例如:'」>' –

回答

0

UPDATE

此基礎上你最後的意見,看來你需要的是這樣的:

$str = '<input type="text" title="this is a fish">'; 
preg_match('/title="(.*)"/', $str, $title); 
$parsed_title = str_replace(' ', '%20', $title[1]); 

但似乎有什麼東西可以做,以提高代碼TRE休息。


你必須使用urlencode或similiar功能:

$str = "Your spaced string"; 
$new = urlencode($str); //Your%20spaced%20string 

或者,使用preg_replace

$str = "Your spaced string"; 
$new = preg_replace("/\s+/", "%20", $str); 

,或在不正規表達式:

$new = str_replace(" ", "%20", $str); 
+0

這並不能幫助我,因爲我有串它是作爲例子,而不僅僅是文字 –

+0

好吧,我已經更新了我的答案。試試'preg_replace'或'str_replace'。然後,檢查dup鏈接 –