I need to know if there's a way in PHP to echo a string with every char.
For instance
/n
and the likes.
Edit for clarification:
When I have a webform and I submit it and I have this text:
I am stupid
and I cannot
explain myself
The text would be like this:
I am stupid /n and I cannot /n explain myself
If I use:
nl2br
I get:
I am stupid <br /> and I cannot <br /> explain myself
Now I have users that input some messed up texts and I need to clean it and put it inside an array. I would love to be able to print to screen every special char such as /n.
I think he means that instead of seeing a newline when a string contains '\n' he wants to see the '\n' as two characters, a '\' and an 'n'.
json_encode works well for this purpose:
echo json_encode("spam\nand eggs");
>> "spam\nand eggs"
Assuming you mean to add \n to every character and $string contains the string you want to edit:
$strarray = str_split($string);
$string = "";
foreach($strarray as $char)
{
$string .= $char."\n";
}
echo $string;
After this $string will contain the original $string with a newline added after every character, and will be echoed. For this to be displayed, you'd have to surround it with <pre> though.
I think he wants to break string into chars and want to print each char in new line. is it ?
Related
Recently ran into a very odd issue where my database contains strings with what appear to be normal whitespace characters but are in fact something else.
For instance, applying trim() to the string:
"TEST "
is getting me:
"TEST "
as a result. So I copy and paste the last character in the string and:
echo ord(' ');
194
194? According to ASCII tables that should be ┬. So I'm just confused at this point. Why does this character appear to be whitespace and how can I trim() characters like this when trim() fails?
It's more likely to be a two-byte 194 160 sequence, which is the UTF-8 encoding of a NO-BREAK SPACE codepoint (the equivalent of the entity in HTML).
It's really not a space, even though it looks like one. (You'll see it won't word-wrap, for instance.) A regular expression match for \s would match it, but a plain comparison with a space won't; nor will trim() remove it.
To replace NO-BREAK spaces with a normal space, you should be able to do something like:
$string = str_replace("\u{c2a0}", " ", $string);
or
$string = str_replace("\u{c2a0}", "", $string);
to remove them
You can try with :
PHP trim
$foo = "TEST ";
$foo = trim($foo);
PHP str_replace
$foo = "TEST ";
$foo = str_replace(chr(194), '', $foo);
IMPORTANT: You can try with chr(194).chr(160) or '\u00A0'
PHP preg_replace
$foo = "TEST ";
$foo = preg_replace('#(^\s+|\s+$)#', '', $foo);
OR (i'm not sure if it will work well)
$foo = "TEST ";
$foo = preg_replace('#[\xC2\xA0]#', '', $foo);
Had the same issue. Solved it with
trim($str, ' ' . chr(194) . chr(160))
You probably got the original data from Excel/CSV.. I'm importing from such format to my mysql db and it took me hours to figure out why it came padded and trim didn't appear to work (had to check every character in each CSV column string) but in fact it seems Excel adds chr(32) + chr (194) + chr(160) to "fill" the column, which at first sight, looks like all spaces at the end. This is what worked for me to have a pretty, perfect string to load into the db:
// convert to utf8
$value = iconv("ISO-8859-15", "UTF-8",$data[$c]);
// excel adds 194+160 to fill up!
$value = rtrim($value,chr(32).chr(194).chr(160));
// sanitize (escape etc)
$value = $dbc->sanitize($value);
php -r 'print_r(json_encode(" "));'
"\u00a0"
$string = str_replace("\u{00a0}", "", $string); //not \u{c2a0}
I needed to trim my string in PHP and was getting the same results.
After discovering the reason via Mark Bakers answer, I used the following in place of trim:
// $str = trim($str); // won't strip UTF-8 encoded nonbreaking spaces
$str = preg_replace('/^(\\s|\\xC2\\xA0)+|(\\s|\\xC2\\xA0)+$/', '', $str);
Thought I should contribute an answer of my own since it has now become clear to me what was happening. The problem originates dealing with html which contains a non-breaking space entity, . Once you load the content in php's DOMDocument(), all entities are converted to their decoded values and upon parsing the it you end up with a non-breaking space character. In any event, even in a different scenario, the following method is another option for converting these to regular spaces:
$foo = str_replace(' ',' ',htmlentities($foo));
This works by first converting the non-breaking space into it's html entity, and then to a regular space. The contents of $foo can now be easily trimmed as normal.
Goal, to trim all text starting with the a left parenthesis '(' from a string. I've read through stack for the last hour, php.net, googled, I've tried using trim, ltrim, rtrim, strpos, preg_replace, etc. Everything that I have found so far has dealt with how to replace the text IF it is a know quantity - mine will vary.
Examples:
Text i want to keep (All of this i want to remove) as well as this...
Example 2:
Text 2 keep (text to remove 123)
Example 3:
Keep Please (123remove)
What is the best way to sanitize this string? The text which follows the first paren will be alphanumeric (letters, numbers, possibly even Exclamation points, etc). The only constant is the first paren '(', anything after i want to trim away/remove.
I am of novice level, I am not yet dealing with classes or jQuery, etc. I wish to do this on the server.
Thank you for any help or guidance.
You can use strpos to find the first parenthesis and substr to get the substring until this position :
$str = 'Test keep (remove) remove';
$pos = strpos($str, '(');
$newString = '';
if ($pos !== false) {
$newString = substr($str, 0, $pos);
}
echo $newString;
Output
Test keep
You were on the right track with preg_replace. You could try the following:
preg_replace('\([^]*', $replacement, $subject)
Tested and works
echo preg_replace('#\(.*#i','',$string_tostrip);
$str =" Text i want to keep (All of this i want to remove)";
$s=explode("(",$str);
$concatinated_str = $s[0];
echo $concatinated_str; // Text i want to keep
Lets suppose I have a string:
$text = "This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD a very long string!"
I want to replace each occurrence of "exec?" in the string with some new text and at the same time I want to store the text that follows "exec" in a separate variable so it can be used when replacing the text.
For example, say I want to replace each occurrence of exec??? with,
< html>???< /html>< div>???< /div>
, so that the resulting string is:
$text2 = "This is my string <html>001</html><div>001</div> and this is the rest of the string <html>222</html><div>222</div> and here is even more <html>SOMEWORD</html><div>SOMEWORD</div> a very long string!"
How can I do this in PHP?
Thanks very much in advance.
Here is a way to go using preg_replace:
$text = "This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD a very long string!";
$text2 = preg_replace('/\bexec(\S+)/', "<html>$1</html><div>$1</div>", $text);
echo $text2,"\n";
This will replace all occurrences of execwhatever.
\S+ stands for any NON space character.
\b is a word boundary.
You may find more info here.
Output:
This is my string <html>001</html><div>001</div> and this is the rest of the string <html>222</html><div>222</div> and here is even more <html>SOMEWORD</html><div>SOMEWORD</div> a very long string!
Update according to comment
If you want to replace more than one string, just do:
$text2 = preg_replace('/\bexec([^:\s]+):([^:\s]+)/', "<html>$1</html><div>$2</div>", $text);
Where [^:\s] means any character that is not semi-colon or space
exec\S+
This regex works replacing all exec words.See demo.
http://regex101.com/r/qK1pK7/1
I have a PHP page which gets text from an outside source wrapped in quotation marks. How do I strip them off?
For example:
input: "This is a text"
output: This is a text
Please answer with full PHP coding rather than just the regex...
This will work quite nicely unless you have strings with multiple quotes like """hello""" as input and you want to preserve all but the outermost "'s:
$output = trim($input, '"');
trim strips all of certain characters from the beginning and end of a string in the charlist that is passed in as a second argument (in this case just "). If you don't pass in a second argument it trims whitespace.
If the situation of multiple leading and ending quotes is an issue you can use:
$output = preg_replace('/^"|"$/', '', $input);
Which replaces only one leading or trailing quote with the empty string, such that:
""This is a text"" becomes "This is a text"
$output = str_replace('"', '', $input);
Of course, this will remove all quotation marks, even from inside the strings. Is this what you want? How many strings like this are there?
The question was on how to do it with a regex (maybe for curiosity/learning purposes).
This is how you would do that in php:
$result = preg_replace('/(")(.*?)(")/i', '$2', $subject);
Hope this helps,
Buckley
In PHP the trim function has a parameter for trimming specific characters (handy for leading zeros and the like). I can't seem to get it to accept a vertical bar (|) character. Anyone know how to get this working? I tried the hex value but had no luck. I'm sure it's something simple.
Cheers
It works for me:
var_dump(trim('|foo|', '|')); // string 'foo' (length=3)
Maybe you have some whitespace around it, or your're using the wrong pipe character? ¦ vs |
Works for me:
$str = "|test string";
echo trim($str, "|");
test string
Can you show some of your code?
Maybe you want to remove a | in the middle of a string
you can use str_replace
str_replace("|", "", $str);
echo trim('|text|', '|'); // returns text
The second param was added in PHP 4.1!
trim() only removes characters from the beginning and end of a string. If you'd like to replace characters in the middle of a string, use str_replace(), or preg_replace() if you like regular expressions.