2014-12-27 6 views
1

Я использовал preg_match_all() для преобразования строки в массив. Рассмотрим строку, как показано нижеКак преобразовать массив в строку в PHP?

$str = "It all starts with an idea. An idea turned into a script that can later be transformed into cartoon characters"; 

и массив, который я получил после использования preg_match_all был

Array ([0] => It all starts [1] => with an idea. [2] => An idea turned [3] => into a script [4] => that can later [5] => be transformed into [6] =>) 

Теперь я хочу, чтобы преобразовать этот массив обратно в строку, я имел прежде. Я попытался использовать implode(), но он говорит

Notice: Array to string conversion in C:\xampp\htdocs\practice\d\d\check.php on line 7 

так как это может сделать. Я использовал PHP.

это то, что я имел обыкновение взрываться()

$contents = implode(" ",$match); 

здесь это мой код:

<?php 

$content = "It all starts with an idea. An idea turned into a script that can later be transformed into cartoon characters"; 

preg_match_all('/((?:\\S+\\s){3})|(.+)$/',$content,$match); 
print_r($match[1]); 
$contents = implode(' ',$match); 
echo $contents; 

?> 

так может кто-то помочь мне ОТУ с ним

спасибо

+2

Эта линия с Implode хорошо. Вы уверены, что это строка 7? Я думаю, что ошибка в другом месте. – GolezTrol

+2

[Preg_match_all] (http://php.net/manual/en/function.preg-match-all.php) возвращает многомерный массив. вы уверены, что ваш массив один размер –

+1

разместите свой код. –

ответ

0

Просто присвойте $match[1] другой переменной:

$arr = $match[1];

Тогда ваш код будет работать следующим образом:

$contents = implode(' ',$arr); 
echo $contents; 

демо here

Вы также можете альтернативно пройти $match[1] взрываться(), но вы можете найти код более читаемым с назначением, которое я рекомендую.

Причина, по которой ваш код был неудачным, состоял в том, что $ match является многомерным массивом, а implode() нуждается в одномерном массиве. Назначая $match[1] другой переменной, вы по существу присваиваете элемент 1 из $ match, который содержит этот массив данных, которые вас интересуют. Что может быть более полезно использовать переменную типа $matches, когда вы будете использовать preg_match_all() в будущем, чтобы напомнить что переменная содержит многомерный массив, когда функция успешна, даже если она находит только одно совпадение! (см. here).

0

вы можете сделать это с взрываются и лопаются функции (если вам не нужно использовать preg_match_all)

$content = "It all starts with an idea. An idea turned into a script that can later be transformed into cartoon characters"; 
$contents_array = explode(" ", $content); // put the string into array , " " is the delimiter 
print_r($contents_array); 
$contents_string_after_array = implode(" ", $contents_array); // convert the array into string , " " is the glue 
echo $contents_string_after_array; 
1

Проблема заключается в implode(' ',$match), которая должна быть как implode(' ',$match[1]).Поскольку $match многомерна массив:

$content = "It all starts with an idea. An idea turned into a script that can later be transformed into cartoon characters"; 
$contents = ""; 

if(preg_match_all('/((?:\\S+\\s){3})|(.+)$/',$content,$match)) { 
    $matches = array_filter($match[1]); 
    //print_r($match[1]); 
    //print_r($matches); 
    $contents = implode(' ', $matches); 
} 

echo $contents; 
2

использование

implode(" ",$match[1]) 

вместо

implode(" ",$match) 

Match многомерна массив

Array 
(
    [0] => Array 
     (
      [0] => It all starts 
      [1] => with an idea. 
      [2] => An idea turned 
      [3] => into a script 
      [4] => that can later 
      [5] => be transformed into 
      [6] => cartoon characters 
     ) 

    [1] => Array 
     (
      [0] => It all starts 
      [1] => with an idea. 
      [2] => An idea turned 
      [3] => into a script 
      [4] => that can later 
      [5] => be transformed into 
      [6] => 
     ) 

    [2] => Array 
     (
      [0] => 
      [1] => 
      [2] => 
      [3] => 
      [4] => 
      [5] => 
      [6] => cartoon characters 
     ) 

) 
Смежные вопросы