Insert a value in a string and check right position - php

I'm trying to figure out a way to solve my problem:
I receive a string like "Hello world.\nHi" and a certain position where I have to add a char.
So the problem is that the position is for a string without \n and I need to find out a way to count those '\n' and define how many '\n's are there before position to increment it.
Here's an example:
$string="Hi\nThis is\na test";
$position=7;
$value=0;
//CODE
$correct_result="Hi\nThis 0is\na test";
$wrong_result="Hi\nThi0s is\na test";
So basically I just need a way to check how many '\n's are there before the position

I solved by using substr from 0 to $position and using count to check if there where "\n"

Related

PHP variables look the same but are not equal (I'm confused)

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

GET string from user and process it

I am getting input from user and performing filter on that input text.
Here is the example : CODE
Problem with this is when I take $s statically it works fine, but when I pass it in this way:
http:/mylocalpi/phone_filter.php?text=%27my%20long%20STRING%20with%20124%20mynumberis%208989243three56%20some%2040one34two3473%27
And get
$s = $_GET['text']; //
// $s = "my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533"; this works fine
Then it does not filter last word. can some one tell what can be issue here?
use this
$s = urldecode($_GET['text']);
As far as I can tell, there is a lack of similarity between the string you use in the constant and the one you send through the URL:
Constant:
$s = "my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533";
URL:
$s = "'my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533'";
Because your URL looks like this:
?text=%27…%27
Which is the same as
?text='…'
As you can see you send an extra pair of ' (%27) that surround your string, you don't need them. Try and see what happens if your static version of the string starts and ends with those '. Your URL should look like this:
?text=my%20long%20STRING%20with%20124%20mynumberis%204054545456%208989243three56%20some%20Numbers%20402three1345233nine3%205023one34533
Without any leading or trailing ' (%27).
It's either that, or try to fix your filter to ignore the ' while processing the string. This is most certainly the cause.

delete all bug string between two words

I've got a script which generates text. I need to be strip all repeated blocks of text. The string is in xml format, so I can use the beginning and ending tags to determine where the strings are. I've been using substr_replace to remove the unnecessary text... However, this only works if I know how many times said text is going to be present in the string. Example :
<container>
<string1>This is the first string.</string>
<string2>This is the second string.</string>
<stuff>This is the important stuff.</stuff>
</container>
That container might appear once, twice six times, seven times, whatever. The point is, it's necessary to only have it appear once in the string variable. Right now this is what I'm doing.
$where_begin = strpos($wsman_output,'<container');
$where_end = strpos($wsman_output,"</container>");
$end_length = strlen("</Envelope>");
$attack = $where_end - $where_begin;
$attack = $attack + $end_length;
$wsman_output = substr_replace($wsman_output,"",$where_begin,$attack);
And I do that for each time the container exists.... However, I just found out that it's not always going to be the same.. Which really messes things up.
Any ideas?
In the end I decided to use the method suggested here.
I pulled each block of string I wanted from the variable, then combined them back together in the required order.

php, string value, length and integer value of a variable don't matche

I am getting a variable from a socket. After reading the respond I am trying to convert the value to a number. if I print the respond it looks correct however when I convert it to number using floor() it doesn't give me the right answer. I also tried to print the length of the variable and it is still not working as it suppose to: This one is for value :185
echo("**************** ".floor($res[0]));
echo "################### $res[0]";
echo "------------- ".strlen($res[0]);
output:
**************** 1################### 185------------- 12
I have also tried stripslashes, trim and also ereg_replace('[:cntrl:]', '',$res[0])
Please try the following: intval($res[0])
You can try also with:
$res = (int)$reg[0];
Hope this helps.
Bye
Ok I found the problem. I saved the value in a file and opened the file using notepad++. I saw the following character in between my string:
SOH,NULL, and bunch of other non character values
What I am assuming is PHP automatically ignore the ASCII values are not show able on the screen (less than 21Hex).

Does PHP str_replace have a greater than 13 character limit?

This works up until the 13th character is hit. Once the str_ireplace hits "a" in the cyper array, the str_ireplace stops working.
Is there a limit to how big the array can be? Keep in mind if type "abgf" i get "nots", but if I type "abgrf" when I should get "notes" I get "notrs". Racked my brain cant figure it out.
$_cypher = array("n","o","p","q","r","s","t","u","v","w","x","y","z","a","b","c","d","e","f","g","h","i","j","k","l","m");
$_needle = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
$_decryptedText = str_ireplace($_cypher, $_needle, $_text);
echo $_decryptedText;
Help?
Use strtrDocs:
$_text = 'abgrf';
$translate = array_combine($_cypher, $_needle);
$_decryptedText = strtr($_text, $translate);
echo $_decryptedText; # notes
Demo
But, was there something I was doing wrong?
It will replace each pair, one pair after the other on the already replaced string. So if you replace a character that you replace again, this can happen:
r -> e e -> r
abgrf -> notes -> notrs
Your e-replacement comes after your r-replacement.
Take a peak at the docs for str_replace. Namely the following line:
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
So it's working as told. It's just doing a circular replacement (n -> a, then a -> n).
Use str_rot13
although it appears to be a straight rot13, if it is not, another option is to use strtr(). You provide a string and an array of replacement pairs and get the resulting translation back.

Categories