Somnath Paul
Somnath Paul

Reputation: 190

Separate each word into a Array

I have a file with contents like :

Apple 100

banana 200

Cat 300

I want to search for a particular string in the file and get the next word. Eg: I search for cat, I get 300. I have looked up this solution: How to Find Next String After the Needle Using Strpos(), but that didn't help and I didn't get the expected output. I would be glad if you can suggest any method without using regex.

Upvotes: 0

Views: 212

Answers (4)

CBusBus
CBusBus

Reputation: 2359

You might benefit from using named regex subpatterns to capture the information you're looking for.

For example you, finding a number the word that is its former (1 <= value <= 9999)

/*String to search*/
$str = "cat 300";
/*String to find*/
$find = "cat";
/*Search for value*/
preg_match("/^$find+\s*+(?P<value>[0-9]{1,4})$/", $str, $r);
/*Print results*/
print_r($r);

In cases where a match is found the results array will contain the number you're looking for indexed as 'value'.

This approach can be combined with

file_get_contents($file);    

Upvotes: 0

Jezen Thomas
Jezen Thomas

Reputation: 13800

I'm not sure this is the best approach, but with the data you've provided, it'll work.

  1. Get the contents of the file with fopen()
  2. Separate the values into array elements with explode()
  3. Iterate over your array and check each element's index as odd or even. Copy to new array.

Not perfect, but on the right track.

<?php
$filename = 'data.txt'; // Let's assume this is the file you mentioned
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
$clean = trim(preg_replace('/\s+/', ' ', $contents));
$flat_elems = explode(' ', $clean);

$ii = count($flat_elems);
for ($i = 0; $i < $ii; $i++) {
    if ($i%2<1) $multi[$flat_elems[$i]] = $flat_elems[$i+1];
}

print_r($multi);

This outputs a multidimensional array like this:

Array
(
    [Apple] => 100
    [banana] => 200
    [Cat] => 300
)

Upvotes: 1

sanj
sanj

Reputation: 444

$find = 'Apple';
preg_match_all('/' . $find . '\s(\d+)/', $content, $matches);
print_r($matches);

Upvotes: 0

toomanyredirects
toomanyredirects

Reputation: 2002

Try this, it doesn't use regex, but it will be inefficient if the string you're searching is longer:

function get_next_word($string, $preceding_word)
{
  // Turns the string into an array by splitting on spaces
  $words_as_array = explode(' ', $string); 

  // Search the array of words for the word before the word we want to return
  if (($position = array_search($preceding_word, $words_as_array)) !== FALSE)
    return $words_as_array[$position + 1]; // Returns the next word
  else
    return false; // Could not find word
}

Upvotes: 0

Related Questions