Php display as a html text the new line \n - php

I'm using echo to display result but the result contains line breaks /n /t /r.
I want to know if the result has is \n or \t or \r and how many. I need to know so I can replace it in a html tag like <p> or <div>.
The result is coming from on other website.
In pattern CreditTransaction/CustomerData:
Email does not contain any text
In pattern RecurUpdate/CustomerData:
Email does not contain any text
In pattern AccountInfo:
I want like this.
In pattern CreditTransaction/CustomerData:
\n
\n
\n
\n\tEmail does not contain any text
\n
In pattern RecurUpdate/CustomerData:
\n
\n
\n
\n\tEmail does not contain any text
\n\tIn pattern AccountInfo:

Your question is quite unclear but I'll do my best to provide an answer.
If you want to make \n, \r, and \t visible in the output you could just manually unescape them:
str_replace("\n", '\n', str_replace("\r", '\r', str_replace("\t", '\t', $string)));
Or if you want to unescape all escaped characters:
addslashes($string);
To count how many times a specific character/substring occurs:
substr_count($string, $character_or_substring);
To check if the string contains a specific character/substring:
if (substr_count($string, $character_or_substring) > 0) {
// your code
}
Or:
if (strpos($string, $character_or_substring) !== false) { // notice the !==
// your code
}
As mentioned earlier by someone else in a comment, if you want to convert the newlines to br tags:
nl2br($string);
If you want to make tabs indenting you could replace all tabs with  :
str_replace("\t", ' ', $string);

Use double quotes to find newline and tab characters.
$s = "In pattern CreditTransaction/CustomerData:
Email does not contain any text
In pattern RecurUpdate/CustomerData: ";
echo str_replace("\t", "*", $s); // Replace all tabs with '*'
echo str_replace("\n", "*", $s); // Replace all newlines with '*'

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

remove all characters after a character using regular expression in php

I need to remove all the characters after the character which I select in a string.
Here is my string
$string = "Blow the fun in the sun.paste a random text";
$new_string = preg_replace("/paste.*/","",$string,-1,$count);
echo $new_string;
My output is Blow the fun in the sun.
If my string is like this
$string = "Blow the fun in the sun.paste \n a random text";
$new_string = preg_replace("/paste.*/","",$string,-1,$count);
echo $new_string;
My output is
Blow the fun in the sun.
a random text
But, I need my output as Blow the fun in the sun. even if there are \n or \t or some other special characters in my strings. How can I match this, while taking those special characters into consideration?
You will need s flag (DOTALL) to make DOT match new lines:
$new_string = preg_replace("/paste.*/"s, "", $string, -1, $count);
Without s flag your regex is not matching new lines as your input contains new lines and you want to replace string that contains new line as well.

Removing various sorts of whitespace in PHP

I am looking to remove multiple line breaks using regular expression. Say I have this text:
"On the Insert tab\n \n\nthe galleries include \n\n items that are designed"
then I want to replace it with
"On the Insert tab\nthe galleries include\nitems that are designed"
So my requirement is:
it will remove all multiple newlines and will replace with one newline
It will remove all multiple spaces and will replace with one space
Spaces will be trimmed as well
I do searched a lot but couldn't find solution - the closest I got was this one Removing redundant line breaks with regular expressions.
Use this :
echo trim(preg_replace('#(\s)+#',"$1",$string));
$text = str_replace("\r\n", "\n", $text); // converts Windows new lines to Linux ones
while (strpos($text, "\n\n") != false)
{
$text = str_replace("\n\n", "\n", $text);
}
That will sort out newline characters.
$text = trim($text);
preg_replace('/\s+/', ' ', $text);
preg_replace('/(?:\s*(?:\r\n|\r|\n)\s*){2}/s', "\n", $text);
Thanks to Removing redundant line breaks with regular expressions

regex: change html before saving in database

Before saving into database i need to
delete all tags
delete all more then one white space characters
delete all more then one newlines
for it i do the following
$content = preg_replace('/<[^>]+>/', "", $content);
$content = preg_replace('/\n/', "NewLine", $content);it's for not to lose them when deleting more then one white space character
$content = preg_replace('/(\&nbsp\;){1,}/', " ", $content);
$content = preg_replace('/[\s]{2,}/', " ", $content);
and finnaly i must delete more then one "NewLine" words.
after first two points i get text in such format-
NewLineWordOfText
NewLine
NewLine
NewLine NewLine WordOfText "WordOfText WordOfText" WordOfText NewLine"WordOfText
...
how telede more then one newline from such content?
Thanks
First of all, while HTML is not regular and thus it is a bad idea to use regular expressions to parse it, PHP has a function that will remove tags for you: strip_tags
To squeeze spaces while preserving newlines:
$content = preg_replace('/[^\n\S]{2,}/', " ", $content);
$content = preg_replace('/\n{2,}/', "\n", $content);
The first line will squeeze all whitespace other than \n ([^\n\S] means all characters that aren't \n and not a non-whitespace character) into one space. The second will squeeze multiple newlines into a single newline.
why don't you use nl2br() and then preg_replace all <br /><br />s with just <br /> then all <br />s back to \n?

Categories