Reputation: 3410
I have the following strings:
Some random 516 text100.
text3.
How could I programmatically obtain something like:
$a[0]["text"] = Some random 516 text
$a[0]["id"] = 100
$a[1]["text"] = text
$a[1]["id"] = 3
Thanks
Upvotes: 0
Views: 93
Reputation: 11992
This works :
$input = array("Some random 516 text100.",
"text3.");
$output=array();
foreach ($input as $text) {
preg_match('/(.*?)(\d+)\./',$text,$match);
array_shift($match); // removes first element
array_push($output,$match);
}
print_r($output);
outputs :
Array
(
[0] => Array
(
[0] => Some random 516 text
[1] => 100
)
[1] => Array
(
[0] => text
[1] => 3
)
)
Upvotes: 3
Reputation: 20753
If your input is this regular you can use a regexps.
note: this version requires a .
under the text<number>
part, you might need to tweak this depending on your input:
$in='Some random 516 text100.
text3.';
preg_match_all('/^(?<text>.*?text)(?<id>\d+)\./im', $in, $m);
$out = array();
foreach ($m['id'] as $i => $id) {
$out[] = array('id' => $id, 'text' => $m['text'][$i]);
}
var_export($out);
The foreach massage the results into the requested format, you might not need that if you can use the one preg_match_all()
returns originally.
Upvotes: 2