Search code examples
phpstringreplaceaiml

Replace some blank space in txt file using PHP


I'm newbie in PHP.

I want to replace some blank space in my txt.file with some word using PHP. This my .txt file (text.txt):

A Chatbot record

Hello, how are you?

I'm Fine

And this what I want

A chatbot record
<category>
<pattern>Hello, how are you?</pattern>
<template>I'm Fine</template>
</category>

I already try some code PHP, with str_replace("&nbsp;","<category><pattern>","\n") but it won't work, what should I do?

Here's failed my experiment:

<?php
$myfile = fopen("text.txt", "r+") or die("Unable to open file!");
str_replace("&nbsp;", "<category><pattern>", "\n"); //I know it's wrong in here, please help me to fix it!
echo fread($myfile,filesize("text.txt"));
fclose($myfile);
?>

Thank you, and sorry for my bad english


Solution

  • Regex is probably the way to go here.

    <?php
    $string = file_get_contents("text.txt");
    
    $replaced = preg_replace("/A Chatbot record(\W+)([^\n]+)\W+([^\n]+)/mi", "A chatbot record\n<category>\n<pattern>$2</pattern>\n<template>$3</template>\n</category>", $string);
    file_put_contents("text.txt", $replaced);
    

    This can match all patterns

    http://sandbox.onlinephpfunctions.com/code/95184665ec627cd9354d67853bb696865d51a03d