Reputation: 111
I have input in that format:
Text number1: 12.3456°, text number2: 78.9012°.
I want replace this to here with PHP:
GPS:12.3456,78.9012: Text number1: 12.3456°, text number2: 78.9012°.
So, again, the input in big text:
"
Bla bla bla, random text, bla bla... Text number1: 12.3456°, text number2: 78.9012°. And more text...
"
This output needed:
"
Bla bla bla, random text, bla bla... GPS:12.3456,78.9012: Text number1: 12.3456°, text number2: 78.9012°. And more text...
"
Output need to append this BEFORE what I searching:
"GPS:12.3456,78.9012:
"
The 2 numbers also in all line different: 12.3456 and 78.9012 All others are fixed. (Spaces, other characters.)
If you just now how to detect and get this line from big text:
"Text number1: 12.3456°, text number2: 78.9012°.
"
Also helps.
If I have this line, I can find numbers and replace.
I will use explode to detect numbers (finding space before and ° after the number) and str_replace to replace the input to output. I know not this is the best way but I know that functions.
(Sorry, text formatting not working as I want. I fixed the input, output, changed "," to space)
Thanks!
Upvotes: 0
Views: 463
Reputation: 593
$text = 'Bla bla bla, random text, bla bla... Text,number1: 12.3456°, text,number2: 78.9012°. And more text... ';
echo preg_replace('%([\w\s,]+:\s(\d+\.\d+)°,\s[\w\s,]+:\s(\d+\.\d+)°)%ui', ' GPS:$2,$3: $1', $text);
//Output: Bla bla bla, random text, bla bla... GPS:12.3456,78.9012: Text,number1: 12.3456°, text,number2: 78.9012°. And more text...
Upvotes: 2
Reputation: 7805
$text = 'Bla bla bla, random text, bla bla...
Text number1: 12.3456°, text number2: 78.9012°.
And more text';
$pattern = '#[a-zá-úàü\d ,]+:\s?([\d.]+)°[^:]+:\s?([\d.]+)°#i';
return preg_replace_callback($pattern, function($match) {
return sprintf("GPS:%s,%s:\n%s.",
$match[1],
$match[2],
$match[0]
);
}, $text);
Upvotes: 1
Reputation: 3342
It's not pretty but I'm late for dinner!
<?
$text = 'Bla bla bla, random text, bla bla...
Text,number1: 12.3456°, text,number2: 78.9012°.
And more text...';
$lines = array();
foreach(explode("\r\n",$text) as $line){
$match = array();
preg_match_all('/\d{0,3}\.?\d{0,20}°/', $line, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
$match[] = $result[0][$i];
}
if(count($match)>0){
$lines[] = 'GPS:'.str_replace('°','',implode(',',$match));
}
$lines[] = $line;
}
echo implode('<br>',$lines);
?>
Bla bla bla, random text, bla bla...
GPS:12.3456,78.9012
Text,number1: 12.3456°, text,number2: 78.9012°.
And more text...
Upvotes: 1