3

I have read few answers on SO, one of this suggests me to do the following but I get array as a result.

Basically we are on the search result and we have this:

$term = $_GET['s'];

if I do echo $term; I get America 2018 while I would like to have:

Location: America
Time: 2018

I tried using explode:

$term = explode("\n", $term); echo $term;

but the result is Array

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
rob.m
  • 9,843
  • 19
  • 73
  • 162

3 Answers3

5

No need to explode it when you can preg_replace. Eg:

$str = "America 2018";
$result = preg_replace("/([A-z]+) (\d+)/", "Location: $1\nTime:$2", $str);
echo $result;

Breakdown:

/([A-z]+) (\d+)/

  • 1st Capturing Group ([A-z]+)
    • Match a single character present in the list below [A-z]+
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    • A-z a single character in the range between A (index 65) and z (index 122) (case sensitive) matches the character literally (case sensitive)
  • 2nd Capturing Group (\d+)
    • \d+ matches a digit (equal to [0-9])
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
3

You can use the snippet below to split in spaces and get the location and time:

$term = explode(" ", $term); 
echo "Location: " . $term[0] . "\n Time: " . $term[1];
Nasser Tahani
  • 725
  • 12
  • 33
  • 1
    nice, this works. I was about to comment that i added
    `$term = explode(" ", $term); echo "Location: " . $term[0] . "
    " ."Time: " . $term[1];`
    – rob.m Mar 26 '18 at 05:35
  • 1
    Thank you, will accept in a minute `$term = explode(" ", $term); echo "

    Location: " . $term[0] . "


    " ."Time: " . $term[1] ."

    "`
    – rob.m Mar 26 '18 at 05:37
3

He want the simple way..

So this is it (just one line)

To make it like America 2018

$term = explode("\n", $term); $term = explode(" ",$term[0])[1]." ".explode(" ",$term[1])[1]; echo $term;

To make it like

Location: America Time: 2018

$term = explode("\n", $term); $term = "Location: ".$term[0].PHP_EOL."Time: ".$term[1]; echo $term;

Cheer

aswzen
  • 1,512
  • 29
  • 46