Jump to content

preg_replace problem


atl_andy

Recommended Posts

Taking a shot that this will be solved.  The following will add (' to the first word in $file.  I need to be able to add ') to the end as well, so ABC will become ('ABC').  However, I can't get it to add (' to all the words.  I tried using g to globally add, but it didn't work. (user error of course)  My thought is to send the results of $str through another for loop to add the ') to the end.  But I'm lost.  Any ideas would be appreciated.

 

<?php
    $file = ("/var/www/html/string.php");
    $lines = file_get_contents($file);

    for ($i=0; $i < count($lines); $i++)
    {
      $str = preg_replace("/^/","(' ",$lines); //I added some spaces for easier reading.
      echo "$str\n";
    }

Link to comment
Share on other sites

Update:  I added m in the regex and it add (' to the beginning of each word in the file.  Now to add it to the end and write the results to a file....

 


<?php
    $file = ("/var/www/html/string.php");
    $lines = file_get_contents($file);

    for ($i=0; $i < count($lines); $i++)
    {
      $str = preg_replace("/^/m","(' ",$lines); //I added the m.
      echo "$str\n";
    }

Link to comment
Share on other sites

Update #2:

 

<?php
    $file = ("/var/www/html/string.php");
    $lines = file_get_contents($file);

    for ($i=0; $i < count($lines); $i++)
    {
      $str = preg_replace("/^/m","(' ",$lines);

    }

     for ($i=0; $i < count($lines); $i++)
    {
      $sta = preg_replace("/$/m"," ') ",$str);
      echo "$str\n";
    }

Link to comment
Share on other sites

That's nice.  I had to modify a bit because some items are alpha-numeric with some dashes.

 

The end result was:

 

echo $lines = preg_replace('/([a-z0-9-]+)/i', "('$1');", $lines);

 

 

And it worked perfectly.  Thanks for your help!  I'm using it to parse text files so I can import into sql.

 

One other question....the results are shown in my broswer like:

 

result result result result

result result result result

 

but I need:

 

result

result

result

 

Any suggestions?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.