I have a form that I have to pull some strings out of. The form uses long dashed lines for dividing data sets. It would be handy to use:
strpos($string, "----")
and
$file2= explode("-----", $file1)
but they don't seem to work. I have replaced the "-" with "." and used "....." in the above to successfully extract the needed data, but it removes wanted dashes, such as 2-year-old, in the extracted data. So I'm back to wanting to use "----" in the code lines above.
I also tried to just replace "--" to ".." but the following doesn't work either.
$string = str_ireplace("--", "..",$string );
Any suggestions would be appreciated.
Thanks.
Is there a way to make this work?
This works perfectly fine.
<?php
$test = 'name----address----2-year-old----dob';
$test_chunks = explode("----", $test);
echo $test_chunks[2];
?>
Displays "2-year-old" w/o any issues. If you must convert the dashes to something else, try this as well:
test_convert = str_replace("----", "....", $test);
...and then explode using periods.
Related
I came across a strange problem in my PHP programming. While using the backtrace function to get the last file the PHP compiler was working with. It would give it to me the path using backslashes. I wanted to store this string in the database, but MySQL would remove them; I'm assuming it was thinking I wanted to escape them.
So C:\Path\To\Filename.php would end up C:PathToFileName.php in the database. When I posted this question to Google, I found many others with the same problem but in many different situations. People always suggested something like:
$str = '\dada\dadda';
var_dump(str_replace('\', '\\', $str));
The problems with this is, even if you put it into a loop of some kind, is that you just keep replacing the first \ with \\. So it starts off like \ then \\\ then \\\\\ then \\\\\\\ then \\\\\\\\\ etc... Until it fills the memory buffer with this huge string.
My solution to this problem, if anyone else has it is:
//$file = C:\Path\To\Filename.php
//Need to use \\ so it ends up being \
$fileArray = explode("\\", $file);
//take the first one off the array
$file = array_shift($fileArray);
//go thru the rest of the array and add \\\\ then the next folder
foreach($fileArray as $folder){
$file .= "\\\\" . $folder;
}
echo $file
//This will give you C:\\Path\\To\\Filename.php
So when it's stored in the database, it will appear to be C:\Path\To\Filename.php.
If anyone else has a better solution to this, I'm all ears.
You need to "double escape" them inside preg_replace parameters (once for the string, once for the regex engine):
$mystring = 'c:\windows\system32\drivers\etc\hosts';
$escaped = preg_replace('/\\\\/','\\\\\\\\',$mystring);
echo "New string is: $escaped\n";
Or only once if you use str_replace:
$newstring = str_replace('\\','\\\\',$mystring);
echo "str_replace : $newstring\n";
?>
mysql_real_escape_string('C:\Path\To\Filename.php');
You can use regex capture group ():
echo preg_replace('/([\\\])/', '${1}${1}', "\b is a metasequence");
// 3 backslahses
// outputs: \\b is a metasequence
Stupid but works for me.
$BS='\\\';
(You put a double backslash in the $BS, but actually you get one backslash only.
$FullName = "C:".$BS.$BS."Path".$BS."To".$BS."FileName.php";
You should get the $FullName "C:\\Path\To\Filename.php"
This may seem odd but I'm simply trying to put a url together.
The first part ($first) I get from user input using strrpos() and substr() with "/".
The exact file I want to get to is fixed ($second) so all I think I need to do is this:
$first = "http://www.somedomain.de/somepath/";
$second = "thexml.xml";
$url = $first.$second;
BUT: Although I use trim() on every part there still is some whitespace between the two parts when I print $url.
When I try to navigate to $url the whitespace is replaced by a "%".
The path itself is correct, when I get rid of the whitespace/ % manually in my browser's adress bar.
I also tried putting the two strings together with an array and implode() but the output stays the same.
What am I doing wrong?
Update from Lisa
ok, so I printed $first and $second separately and there are no whitespaces. it seems to be appearing when I concatenate them and exactly where the two strings are put together.
Any other ideas?
ok, so I printed $first and $second separately and there are no whitespaces. it seems to be appearing when I concatenate them and exactly where the two strings are put together.
Any other ideas?
Most likely, the code you're editing or the inputs (user, database, etc.) is not what you expect. Try trimming down (no pun intended) the code to a minimal example. For example, go from
$first = "http://www.somedomain.de/somepath/";
$second = "thexml.xml";
$url = $first.$second;
echo $url; // No space
to
$first = $_POST['url'];
$second = "thexml.xml";
$url = $first.$second;
echo $url; // If this contains a space, the input contains the offending space
step-by-step to find the mistake.
Have you tried rawurlencode? http://php.net/rawurlencode
I know this is a very old question but I just had this similar issue and was finally able to find a solution.
My solution is to use the trim function like this:
$url = trim($first).$second;
I've got some data that needs to be cleaned up into a fixed length format. I'm using PHP to grab the data out, covert it, and put it back in, but it's not working as planned. There is a certain point in each piece in the middle of the data where there should be spaces to increase the length to the proper amount of characters. The code I'm using to do this is:
while ($row = mysql_fetch_array($databasetable)) {
$key = $row['KEY'];
$strlength = strlen($key);
while ($strlength < 33) {
$array = explode(' TA',$key);
$key = $array[0] . ' TA' . $array[1];
$strlength++;
}
}
It's taking a ' TA' and adding two spaces before it, rinse and repeat until the total length is 33, however when I output the value, it just returns a single space. Funny part is that even though it is displaying a single space, it returns a strlen of 33 even if it's not displaying 33 characters.
Any help in figuring this out would be greatly appreciated.
HTML will have extra spaces filtered out.
To force extra spaces to be shown, use ' ' rather than ' '.
#TVK- is correct, HTML ignores multiple-space whitespace - it'll turn it into one space.
In addition to his solution, you can use the CSS instruction white-space: pre to preserve spaces.
Remember that, when doing an output to a webbrowser, it'll interpret it as HTML ; and, in HTML, several blank spaces are displayed as one.
A possibility would be to use the var_dump() function, especially if coupled with the Xdebug extension, to get a better idea of your data -- or to display it as text, sending a text-related content-type.
BTW : if you want to make sure a string contains a certain amount of characters, you'll probably want to take a look at str_pad()
Easiest options for you I think are
Wrap your output in <pre> tags
replace each space with
If you're rendering HTML, consecutive spaces will be ignored. If you want to force rendering of these, try using
Generally using multiple non breakable spaces one after another is a bad idea and might not bring a desired result unless you're using a monospaced font. If you want to move some piece of text to a certain position on your page, consider using margins
You can tell the browser that the text is preformatted
this text will be displayed as it is formatted
spaces should all appear.
new lines will also be apparent
Have you looked into str_pad? something like :
str_pad ( 'mystring' , 33 , ' TA' , STR_PAD_LEFT );
I thing you can use str_repeat
echo str_repeat(" ", 15);
I've tried about everything to delete some extra \n characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.
And yes I've tried things like
In JS:
text.replace(/\n/g,"")
In PHP:
preg_replace("[\n]","",$result);
str_replace("\n","",$result);
and when I try
text.replace(/\n/g,"")
in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.
I'm desperate, picky and this is killing me. Any input is appreciated.
EDIT:
If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.
Answer Explanation:
Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!
In my case:
Why this works? str_replace('\n', '', $result)
And this doesn't? str_replace("\n", '', $result)
Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.
If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.
In php, use str_replace(array('\r','\n'), '', $string).
I guess the problem is you also have \r's in your code (carriage returns, also displayed as newlines).
In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.
text = text.replace(/\n/g,"")
Both of the PHP functions you tried return the altered string, they do not alter their arguments:
$result = preg_replace("[\n]","",$result);
$result = str_replace("\n","",$result);
Strangely, using
str_replace(array('\r','\n'), '', $string)
didn't work for me. I can't really work out why either.
In my situation I needed to take output from the a WordPress custom meta field, and then I was placing that formatted as HTML in a javascript array for later use as info windows in a Google Maps instance on my site.
If I did the following:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= str_replace(array('\r','\n'), '', $stockist_address);
This did not give me a string with the html on a single line. This therefore threw an error on Google Maps.
What I needed to do instead was:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= trim( preg_replace( '/\s+/', ' ', $stockist_address ) );
This worked like a charm for me.
I believe that usage of \s in regular expressions tabs, line breaks and carriage returns.
I'm using str_replace and it's not working correctly.
I have a text area, which input is sent with a form. When the data is received by the server, I want to change the new lines to ",".
$teams = $_GET["teams"];
$teams = str_replace("\n",",",$teams);
echo $teams;
Strangely, I receive the following result
Chelsea
,real
,Barcelona
instead of Chealsea,real,Barcelona.
What's wrong?
To expand on Waage's response, you could use an array to replace both sets of characters
$teams = str_replace(array("\r\n", "\n"),",",$teams);
echo $teams;
This should handle both items properly, as a single \n is valid and would not get caught if you were just replacing \r\n
Try replacing "\r\n" instead of just "\n"
I would trim the text and replace all consecutive CR/LF characters with a comma:
$text = preg_replace('/[\r\n]+/', ',', trim($text))
I had the same issue but found a different answer so thought I would share in case it helps someone.
The problem I had was that I wanted to replace \n with <br/> for printing in HTML. The simple change I had to make was to escape the backslash in str_replace("\n","<br>",($text)) like this:
str_replace("\\n","<br>",($text))