-2

I have the following code in PHP, which searches a file for lines containing a string:

<?php
echo "Results for: ";
echo ($_POST['query']);
echo "<br><br>";
$file = 'completed.db';
$searchfor = ($_POST['query']);
header('Content-Type: text/plain');
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}
?>

In the line, echo implode("\n", $matches[0]); in echos an array, separated by spaces. If I wanted to separate the items by a different string, say $entry = '<br>', how would you do it?

For example, if $matches was

  • one
  • two
  • three

Then, the command should echo:

one<br>two<br>three<br>
2

2 Answers 2

0

Just add the break tag to the string

echo implode("\n<br>", $matches[0]);

And one more to trail since implode only goes between.

echo "<br>";
Sign up to request clarification or add additional context in comments.

Comments

0

The following code simply uses implode with a different first argument, bu also adds the separator to the end (as per specification)

$entry = '<br>';
echo implode($entry, $matches[0]).$entry;

1 Comment

Could you explain how your answer addresses the problem(s) from the question? Code-only answers are not very useful, especially for further readers that stumble upon this post. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.