2015-03-25 68 views
-4

除去替代字符我有字符串假設如何從一個PHP串

$str = "abcdefghijklmno"; 

,我想像

$new_str = "acegikmo"; 

字符串我需要使用如果可能的PHP的功能的任何組合的最短方法。

+0

^嗯,這聽起來像你只是想一些代碼。你有沒有嘗試過至少一些東西? – Rizier123 2015-03-25 09:51:55

+1

str_replace(array('a','d',....'z'),「」,$ new_str); – degr 2015-03-25 09:52:07

+0

1.您可能從答案中注意到,如果您想要刪除字符串中的每個第二個字符或特定字母,例如d,e,... 2.您仍然沒有回答:*您是否嘗試過至少一些?*,但您似乎只想讓您的代碼 – Rizier123 2015-03-25 10:16:26

回答

0

您可以刪除一個字符串的每個第2個字符:

$str = "abcdefghijklmno"; 
$str = preg_replace("/(\w)\w/","$1",$str); 

例子:

abcdefghijklmno will become acegikmo 
1234567890 will become 13579 
1

嘗試下面的代碼

$string = 'teststring'; //if you want odd places characters then add whitespace at the starting of the string i.e ' teststing' 
$array= str_split($string,1); 
$new_string = ''; 
foreach($array $key=>$data){ 
if($key&1){ 
      $new_string .= $data; 
    } 
} 
echo $new_string; 
+0

工作,但marc解決方案更好。 – 2015-03-25 10:07:28

+0

@AniketSingh - 是的,但僅限於該字符串。它被稱爲硬核編碼。 – 2015-03-25 10:09:11

0

用下面的代碼

$string = 'abcdefghijklmno'; 
 
$new_str = ''; 
 
for($i=0;$i<=strlen($string); $i++){ 
 
    if($i%2!=0){ 
 
    $new_str.=$string[$i-1]; 
 
    } 
 
} 
 

 
echo $new_str;

+1

非常不靈活的解決方案!這隻適用於1個情況 – Rizier123 2015-03-25 10:02:35

+0

字符串是不同的,這只是一個例子。 – 2015-03-25 10:06:09

+0

我已經回答了你問的問題,如果你想做一些不同的事情,然後正確地問問題。 – 2015-03-25 10:06:35

0

如果你正在運行PHP 5.6您可以使用array_filter

$string = "abcdefghijklmno"; 

$newstring = join("", 
       array_filter 
       (
        str_split($string), 
        function($k) { 
         return ($k % 2 == 0); 
         }, 
        ARRAY_FILTER_USE_KEY 
       ) 
      ); 
//acegikmo 

http://ideone.com/HC7eL0