Nika Gelashvili Nika Gelashvili - 6 months ago 10
PHP Question

Multi-array with one output

Here is my code, which currently does not working properly. How can I make it working? My wish is to make output like one string (of course I know how to "convert" array to string):


words altered, added, and removed to make it


Code:

<?php

header('Content-Type: text/html; charset=utf-8');
$text = explode(" ", strip_tags("words altered added and removed to make it"));
$stack = array();

$words = array("altered", "added", "something");
foreach($words as $keywords){
$check = array_search($keywords, $text);
if($check>(-1)){
$replace = " ".$text[$check].",";
$result = str_replace($text[$check], $replace, $text);
array_push($stack, $result);
}
}

print_r($stack);
?>


Output:

Array
(
[0] => Array
(
[0] => words
[1] => altered,
[2] => added
[3] => and
[4] => removed
[5] => to
[6] => make
[7] => it
)

[1] => Array
(
[0] => words
[1] => altered
[2] => added,
[3] => and
[4] => removed
[5] => to
[6] => make
[7] => it
)
)

Answer

Without more explanation it's as simple as this:

$text  = strip_tags("words altered added and removed to make it"); 
$words = array("altered", "added", "something"); 

$result = $text;
foreach($words as $word) {
    $result = str_replace($word, "$word,", $result);
}
  • Don't explode your source string
  • Loop the words and replace the word with the word and added comma

Or abandoning the loop approach:

$text   = strip_tags("words altered added and removed to make it"); 
$words  = array("altered", "added", "something"); 

$result = preg_replace('/('.implode('|', $words).')/', '$1,', $text);
  • Create a pattern by imploding the words on the alternation (OR) operator |
  • Replace found word with the word $1 and a comma
Comments