How to delete multiple spaces in .txt from PHP - 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

Related

regex replace all occurances of one character?

Lots of topics on this but i can't figure it out, looking for some tips, shouldn't be that difficult.
I have filename:
test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg
i'm trying to use regex to replace the characters _ and then everything starting from snapshot
I got snapshot covered, but i can't seem to get how to catch all the occurances of _ to be selected
(_)(snapshot)(.*)
selects only 1 _
I read that . should select "any single character" not sure how to use this properly or if it is what i am looking for.
Any guidance would be great! (this is probably 100% a dupe but i have checked all the suggested threads without finding the solution to this seemingly easy problem!)
Can't comment yet, but for regex to match more than one occurrence, you need the g - global modifier.
/(_snapshot.*$|_|\.)/gi
https://regex101.com/r/aI7fF8/2
If you replace purely with space all matching occurences, remember to trim last space.
Here's a php sample as well
<?php
$str = "test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg";
$res = preg_replace(array("/_snapshot.*$/", "/[_.]/"), array("", " "), $str);
print $res; // test file from mpc mp4
snapshot.*$|[_.]
You can try this.Replace by space.See demo.
https://regex101.com/r/mT0iE7/13
$re = "/snapshot.*$|[_.]/im";
$str = "test_file_from_mpc.mp4_snapshot_13.29_[2015.05.13_21.10.11].jpg";
$subst = " ";
$result = preg_replace($re, $subst, $str);
Another (potentially faster, but not prettier) way would be to use explode() & implode().
// Split string by underscores
$pieces = explode('_', $filename);
// Get the number of pieces
$n = count($pieces);
// Keep just the file extension in the last piece
$pieces[$n] = substr($pieces[$n], strpos($pieces[$n], '.'));
// Remove the other unwanted pieces
unset($pieces[$n - 1];
unset($pieces[$n - 2];
// Reassemble with spaces instead of underscores
$new_string = implode(' ', $pieces);

Php display as a html text the new line \n

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 '*'

PHP Regex: Remove words less than 3 characters

I'm trying to remove all words of less than 3 characters from a string, specifically with RegEx.
The following doesn't work because it is looking for double spaces. I suppose I could convert all spaces to double spaces beforehand and then convert them back after, but that doesn't seem very efficient. Any ideas?
$text='an of and then some an ee halved or or whenever';
$text=preg_replace('# [a-z]{1,2} #',' ',' '.$text.' ');
echo trim($text);
Removing the Short Words
You can use this:
$replaced = preg_replace('~\b[a-z]{1,2}\b\~', '', $yourstring);
In the demo, see the substitutions at the bottom.
Explanation
\b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string)
[a-z]{1,2} matches one or two letters
\b another word boundary
Replace with the empty string.
Option 2: Also Remove Trailing Spaces
If you also want to remove the spaces after the words, we can add \s* at the end of the regex:
$replaced = preg_replace('~\b[a-z]{1,2}\b\s*~', '', $yourstring);
Reference
Word Boundaries
You can use the word boundary tag: \b:
Replace: \b[a-z]{1,2}\b with ''
Use this
preg_replace('/(\b.{1,2}\s)/','',$your_string);
As some solutions worked here, they had a problem with my language's "multichar characters", such as "ch". A simple explode and implode worked for me.
$maxWordLength = 3;
$string = "my super string";
$exploded = explode(" ", $string);
foreach($exploded as $key => $word) {
if(mb_strlen($word) < $maxWordLength) unset($exploded[$key]);
}
$string = implode(" ", $exploded);
echo $string;
// outputs "super string"
To me, it seems that this hack works fine with most PHP versions:
$string2 = preg_replace("/~\b[a-zA-Z0-9]{1,2}\b\~/i", "", trim($string1));
Where [a-zA-Z0-9] are the accepted Char/Number range.

How do you strip whitespace from user submitted data that is not an array PHP?

I was wondering how can I strip white space from elements that are just whitespace and whitespace from all elements from user submitted data using PHP?
lets say if a tag is stripped how can
I stop that from entering the
database?
$sRaw = $_POST[ 'data' ];
$sTrimmed = trim( $sRaw );
if( $sRaw === $sTrimmed ) {
// DB insert code
} else {
// Message was trimmed, show user an error
}
Very simple.
$string = " Whats up I'm cool?";
$string = trim($string);
$string = str_replace(" ", " ", $string);
$string = str_replace(" ", " ", $string);
echo $string; //output is "Whats up I'm cool?"
The reason is for this is because trim() removes any whitespace which is deemed useless thus reducing the total size of the string. The only thing is trim() only removes the whitespace at the beginning and end, so I've added two str_replace() which have been set to remove unwanted whitespace, and because if there's " " (three spaces) one str_replace() won't cut it so I've added it twice, and if you want to, you can add a cycle using foreach() which will trim it until there's no whitespace left but I have wrote it in the basic form as that's what you're asking for.
Depends on the white space... but I believe you are asking about trim() which removes starting and ending whitespace.
echo trim(" v "); //results in "v"

Remove excess whitespace from within a string

I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can't find a way to remove the excess white space from between the strings.
What would be the best way to remove the inner whitespace characters?
Not sure exactly what you want but here are two situations:
If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.
If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".
Example:
$foo = preg_replace('/\s+/', ' ', $foo);
$str = str_replace(' ','',$str);
Or, replace with underscore, & nbsp; etc etc.
none of other examples worked for me, so I've used this one:
trim(preg_replace('/[\t\n\r\s]+/', ' ', $text_to_clean_up))
this replaces all tabs, new lines, double spaces etc to simple 1 space.
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extra spaces, as well as leading and trailing spaces.
If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . "
And you expect the answer to be
"this string have lots of space", you can use the following solution:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.
In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.
function secureRip(string $str): string { /* Rips all whitespace securely. */
$arr = str_split($str, 1);
$retStr = '';
foreach ($arr as $char) {
$retStr .= trim($char);
}
return $retStr;
}
$str = preg_replace('/[\s]+/', ' ', $str);
You can use:
$str = trim(str_replace(" ", " ", $str));
This removes extra whitespaces from both sides of string and converts two spaces to one within the string. Note that this won't convert three or more spaces in a row to one!
Another way I can suggest is using implode and explode that is safer but totally not optimum!
$str = implode(" ", array_filter(explode(" ", $str)));
My suggestion is using a native for loop or using regex to do this kind of job.
To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this
? productID =26%20via%20#LFS
Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.
$productID=preg_replace('/[\s]+.*/','',$productID);
I look for a space in the URL and then remove everything after it.
I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str))).
Laravel 9.7 intruduced the new Str::squish() method to remove extraneous whitespaces including extraneous white space between words: https://laravel.com/docs/9.x/helpers#method-str-squish
$str = "I am a PHP Developer";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
if (isset($str_arr[$i + 1]) && $str_arr[$i] == ' ' && $str_arr[$i] == $str_arr[$i + 1]) {
unset($str_arr[$i]);
}
else {
continue;
}
}
echo implode("", $str_arr);

Categories