I have开发者_C百科 a text file in which each line is an entry. each line has certain words separated by space and 2 -3 words at the end of the entry with brackets
eg.
asd asdasd asdasd {m} [jsbbsdfb]
how do I get the following result in php
$data[0]="asd asdasd asdasd"
$data[1]= "{m}"
$data[2]= "[jsbbsdfb]"
You can use substring
and strpos
to find the right parts or you can use preg_match
(regular expressions), both have their own (dis)advantages. Using preg_match
you can do this is as little as one line, but it is relatively slow and not as easy to use. I would do something like this:
while(/* $line is next line available */) {
$brace_position = strpos($line, '{');
$bracket_position = strpos($line, '[');
$data = array(
substr($line, 0, ($brace_position - 1),
substr($line, $brace_position, ($backet_position - $brace_position - 1)),
substr($line, $bracket_position)
);
}
The other answer provided above, by wired00, are correct too, but only if each line is exactly the same in length (i.e. the same amount of words an spaces). The answer by check123 is not a correct answer to your question.
See strauberry's answer for the regular expression which I mentioned in above.
$regex = '/([a-zA-Z ]*) (\{[a-zA-Z]\}) (\[[a-zA-Z]+\])/';
$yourText = "asd asdasd asdasd {m} [jsbbsdfb]";
$lines = explode("\n", $yourText);
foreach($lines as $line) {
$result = array();
preg_match($line, $regex, $result);
print_r($result);
}
You can tune the regex of course :)
few ways... you could try exploding on the spaces... then concatenate the first 3 array elemnents together
something like this:
$yourString = "asd asdasd asdasd {m} [jsbbsdfb]";
$elements = explode ( " " , $yourString);
$string1 = $elements[0] . $elements[1] . $elements[2];
$string2 = $elements[3];
$string3 = $elements[4];
you could obviously then just set the values into first 3 elements of the array if you wanted
ie:
$yourString = "asd asdasd asdasd {m} [jsbbsdfb]";
$elements = explode ( " " , $yourString);
$elements[0] = $elements[0] . $elements[1] . $elements[2];
$elements[1] = $elements[3];
$elements[2] = $elements[4];
$x = "asd asdasd asdasd {m} [jsbbsdfb]";
$a1 = strpos($x, '{');
$a2 = strpos($x, '}', $a1);
$b1 = strpos($x, '[', $a2);
$b2 = strpos($x, ']', $b1);
$data = array();
$data[] = substr($x, 0, $a1-1);
$data[] = substr($x, $a1+1, $a2-$a1-1);
$data[] = substr($x, $b1+1, $b2-$b1-1);
var_dump($data);
$a = explode(" ",$string);
$a[1] //will store first word of your string
$a[2] // and so on until the end of the string
Ok! I got it wrong above. You might want to try something like:
$str = "asd asdasd asdasd {m} [jsbbsdfb]";
$k=strlen($str);
for($i=0;$i<$k;$i++) {
$char = substr($str,$i,1);
//do your operation here on
}
and loop through each character of the string and operate as required.
精彩评论