Anoop Sonkar
Anoop Sonkar

Reputation: 49

Text file as single string in PHP code

my text file is like this:

atagatatagatagtacataacta\n
actatgctgtctgctacgtccgta\n
ctgatagctgctcgctactacgat\n
gtcatgatctgatctacgatcaga\n

I need this file in single string or in single line in both same and reverese order like this:

atagatatagatagtacataactaactatgctgtctgctacgtccgtactgatagctgctcgctactacgatgtcatgatctgatctacgatcaga

and "reverese" (for which I didn't write code because I need help ).
I am using:

<?php
    $re = "/[AG]?[AT][AT]GAGG[ATC]GC[GA]?[ATGC]/"; 

    $str = file_get_contents("filename.txt");
    trim($str);

    preg_match($re, $str, $matches);
    print_r($matches);
?>

Upvotes: 0

Views: 67

Answers (1)

Mario A
Mario A

Reputation: 3363

You can remove spaces and newlines using preg_replace, and you can reverse a string using strrev.

$yourString = "atagatatagatagtacataacta\n actatgctgtctgctacgtccgta\n ctgatagctgctcgctactacgat\n gtcatgatctgatctacgatcaga\n";    
$stringWithoutSpaces = preg_replace("/\s+/", "", $yourString);
$stringReversed = strrev($stringWithoutSpaces);
echo $stringReversed;

http://php.net/manual/de/function.preg-replace.php

http://php.net/manual/en/function.strrev.php

Explanation: With preg_replace you replace any character in $yourString with an empty string "" that matches the search pattern "/\s+/". The \s in the search pattern stands for any whitespace character (tab, linefeed, carriage return, space, formfeed), the + is there to match also multiple whitespace characters, not just one.

Upvotes: 1

Related Questions