简体   繁体   中英

PHP - Searching for string in text file and turn the whole line into an array

I was wondering how I would go about searching for a string in a text file and then turning the whole line the string is contained in into an array. To make this less wordy, I'll just give an example.

sometext0:Test:sometext123
sometext0:Test14:sometext123
sometext0:test44:sometext123

The string in this case would be "Test14" (second line). What should be done, is search for the "Test14". Once this is done, it should take the whole line into a string, and based off of this, turn the line into an array per delimiter.

Array[0] would be "sometext0", Array[1] would be "Test14", and Array[2] would be "sometext123" Thank you!

To get the entire line that the desired word is on, you can use strstr() and pass in a -1 value for the third parameters. To split the line into an array, you can use explode() on the colon.

This can be seen in the following:

<?php

$input = "sometext0:Test:sometext123
sometext0:Test14:sometext123
sometext0:test44:sometext123";

$target = "Test14";
$target_line = strstr($input, $target, -1);

var_dump(explode(":", $target_line));

Which returns:

array(4) {
  [0]=>
  string(9) "sometext0"
  [1]=>
  string(4) "Test"
  [2]=>
  string(21) "sometext123
sometext0"
  [3]=>
  string(0) ""
}

This can be seen working here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM