How to trim each line in a heredoc (long string) in PHP - php

I'm looking to create a PHP function that can trim each line in a long string.
For example,
<?php
$txt = <<< HD
This is text.
This is text.
This is text.
HD;
echo trimHereDoc($txt);
Output:
This is text.
This is text.
This is text.
Yes, I know about the trim() function, but I am just not sure how to use it on a long strings such as heredoc.

function trimHereDoc($t)
{
return implode("\n", array_map('trim', explode("\n", $t)));
}

function trimHereDoc($txt)
{
return preg_replace('/^\s+|\s+$/m', '', $txt);
}
^\s+ matches whitespace at the start of a line and \s+$ matches whitespace at the end of a line. The m flag says to do multi-line replacement so ^ and $ will match on any line of a multi-line string.

Simple solution
<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);

function trimHereDoc($txt)
{
return preg_replace('/^\h+|\h+$/m', '', $txt);
}
While \s+ removes empty lines, keeps \h+ each empty lines

Related

PHP Remove extra spaces between break lines

I have a string in PHP, i'm able to remove multiple continuous break lines and multiple spaces, but what i'm still not able is to remove multiple break lines if i have an space in the middle.
For example:
Text \r\n \r\n extra text
I would like to clean this text as:
Text \r\nextra text
Could also be too:
Text \r\n \r\nextra text
Don't need to be an extra espace after the break line.
What i have right now is:
function clearHTML($text){
$text = strip_tags($text);
$text = str_replace(" ", " ", $text);
$text = preg_replace("/[[:blank:]]+/"," ",$text);
$text = preg_replace("/([\r\n]{4,}|[\n]{2,}|[\r]{2,})/", "\r\n", $text);
$text = trim($text);
return $text;
}
Any suggestions?
To remove extra whitespace between lines, you can use
preg_replace('~\h*(\R)\s*~', '$1', $text)
The regex matches:
\h* - 0 or more horizontal whitespaces
(\R) - Group 1: any line ending sequence (the replacement is $1, just this group vaue)
\s* - one or more whitespaces
The whitespace shrinking part can be merged to a single preg_replace call with the (?: |\h)+ regex that matches one or more occurrences of an string or a horizontal whitespace.
NOTE: If you have Unicode texts, you will need u flag.
The whole cleaning function can look like
function clearHTML($text){
$text = strip_tags($text);
$text = preg_replace("~(?: |\h)+~u", " ", $text);
$text = preg_replace('~\h*(\R)\s*~u', '$1', $text);
return trim($text);
}

How to delete multiple spaces in .txt from PHP

this is my txt file
I'm adding data from .txt to database with this code:
$dosya=new SplFileObject('veriler.txt');
while(!$dosya->eof())
{
    $satir=$dosya ->fgets();
    list($name,$section,$initialname)=explode(' ',$satir);
     
   $sth= $baglan->prepare('INSERT INTO tablo1 values (NULL,?,?,?,NULL)');
    $sth->bindValue(1,$name,PDO::PARAM_STR);
    $sth->bindValue(2,$section,PDO::PARAM_INT);
    $sth->bindValue(3,$initialname,PDO::PARAM_STR);
    $sth->execute();
     
}
In the .txt if there is a 1 space between the words, my program is working. But as you can see, there are more than one space in my txt file. How can i delete/remove multiple spaces in .txt file? If you can show me in my codes, i will be glad. Thank you.
You can use a regular expression as well to archive the same result.
<?php
// Your code here!
$string = "This has too many spaces";
$result = preg_replace("/\s{2,}/", ' ', $string);
echo($result);
?>
Where /\s{2,}/ means after 2 spaces replace it with a single space also consider that \s also means any of the following characters:
\r
\n
\t
\f
\v
(empty space)
Link: https://paiza.io/projects/M6eSG1zHIUdG5IZEXFZQog
\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.
You can read more about this over here: https://www.regular-expressions.info/shorthand.html
explode() the string, remove array elements with whitespace, and implode():
<?php
$string = "This has too many spaces";
$array = explode(" ", $string);
$array = array_filter($array);
$result = implode(" ", $array);
echo($result);
?>
https://paiza.io/projects/Bi-2H7HiPIklLwXGfYAqCg
#Crisoforo Gaspar solution in your code :
$dosya=new SplFileObject('veriler.txt');
while(!$dosya->eof())
{
$satir=$dosya ->fgets();
$satirWithoutManySpaces = preg_replace("/\s{2,}/", ' ', $satir);
list($name,$section,$initialname)=explode(' ',$satirWithoutManySpaces);
$sth= $baglan->prepare('INSERT INTO tablo1 values (NULL,?,?,?,NULL)');
$sth->bindValue(1,$name,PDO::PARAM_STR);
$sth->bindValue(2,$section,PDO::PARAM_INT);
$sth->bindValue(3,$initialname,PDO::PARAM_STR);
$sth->execute();
}
Hope this help

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);
?>
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.

Remove white space from first line of textarea

how can i prevent php to remove the whitespace from the begining of the textarea first line. Everytime i submited the form, the withespace are removed...even if i replace it for nbsp;
The code i'm using:
PHP
if(isset($_POST['btn_cel'])){
$text = trim($_POST['cel']);
$text = explode("\n", $text);
foreach($texto as $line){
echo str_replace(' ',' ',$line);
}
}
The input
1234 5678
abcdefghif
The output
1234 5678
abcdefghif
Get rid of the call to trim.
This function returns a string with whitespace stripped from the beginning and end of str.
From the PHP documentation :
trim — Strip whitespace (or other characters) from the beginning and end of a string
You should not be using the trim() function if you want php to leave whitespaces as it is. If you apply trim on some string it removes whitespaces from the beginning and end of it.
if(isset($_POST['btn_cel'])){
$text = trim($_POST['cel']);
$text = explode("\n", $text);
foreach($texto as $line){
echo trim(str_replace(' ',' ',$line));
}
}

How can I get the first non-white space character of a line using php

I have a line that typically starts with a few spaces as the lines are in columns and use a monospace font to make things line up. I want to check if the first non-white space character (or even just the first thing that isn't a space) and see if that is a number. What is the least server intensive way of doing this?
You can use trim() (or ltrim() in this case) to delete the whitespace, and make use of the array access of strings:
$line = ltrim($line);
is_numeric($line[0]);
You can use a regular expression:
if (preg_match('/^\s*(\S)/m', $line, $match)) {
var_dump($match[0]);
}
Or you remove any whitespace at the begin and then get the first character:
$line_clean = ltrim($line);
var_dump(substr($line_clean, 0, 1));
if (preg_match('/^\s*\d/', $line)) {
// ^ starting at the beginning of the line
// \s* look for zero or more whitespace characters
// \d and then a digit
}
$first = substr(trim($string), 0, 1);
$is_num = is_numeric($first);
return $is_num;
Try RegEx:
$Line = ...;
preg_match('/^[:space:]*(.)/', $Line, $matches);
$FirstChar = $matches[0];

Categories