I have been trying to figure this out for some hours now.... I have to do some regex search and replace in a txt file before I can import it to mysql. Here is what I have in the text file: hello some random words 55 anotherhello different number of words and spaces 56 andanotherhello one word 57 I need to cut out everything that comes after the first word in a line and before the number in that line and replace it with a comma. The final data should look like this: hello,55 anotherhello,56 andanotherhello,57 Can any regex pro help me out with this? Would be awesome.
Not really regex, but should work: <?php $filename = 'FILENAME'; $l = file($filename); foreach ($l as $line) { $firstword = explode(' ', $line); $firstword = $firstword[0]; preg_match("/(?<=\040)([^\s]+?)$/",trim($line),$lastnumber); echo $firstword.','.$lastnumber[0]."\n"; } ?> PHP: my test run:
Krsix you rock thank you! If I can't figure the regex out I will do it along with php like you did. Great! Anyway I would still love to figure it out as I try to learn more about regex and this is the one I have so far: \s(?!\r)(.*?)\s(?=\d) The problem here is that it also matches the line breaks. *Edit: Got it... finally... \s(?<!\n)(.*?)\s(?=\d)