Does PHP str_replace have a greater than 13 character limit? - php

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.

Related

Insert a value in a string and check right position

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"

I am getting a error using php (str_replace)

I am getting a error while using php str_replace function.
I am reading out a string in a different file a JSON
and if I remove the str_replace part it works without the error but I want to make the ** go to bold if there are any other ways you know you can also just tell that.
<?php
$data = json_decode($readjson, true);
echo "<br/><br<br/>";
foreach ($data as $emp) {
echo str_replace("**","<strong>","$data"), $emp['message']."<br/>";
}
?>
And the output is
Notice: Array to string conversion in C:\Users\k-ver\Dropbox\Other\website stuff or smth\r3mind3r\changelog.php on line 16
Array - Weekley Update - Another great week at our side! We have made enournous advances in synching with the raspberry pi (the computer we are going to host from) and are closer than ever to our promised release We have also been fixing on the mute commands and are very close to making it work, aswell with unmute command.language feature is closing up on complete and about 70% of the bot has the language system working. We also made a new system that should be easier to use for bouth us devs and the translators. All thats left for the release atm is: -finishing synching -fixing the mute command and unmute command -make a functioning permissonlevel system -adding those last 30% of the bot that does not have the translationsystem in place. and the bot will have its huge release! (about time if you asked me)
(it is for a dev log)
and the part I don't understand is the notice and I also don't understand how to fix it
It would be awesome if you guys would like to help me.
This variable should be string value e.g $emp['message'] not the multi-dimensional array $data.
// see this line with $emp['message'] not $data array
str_replace("**","<strong>",$emp['message']);
EDIT: As per comment
<?php
$string = '{
"188762891137056769": {
"message": "\n**- Weekley Update -**\nAnother great week at our side! \nWe have made enournous advances in synching with the raspberry pi *(the computer we are going to host from)* and are closer than ever to our promised release\n\nWe have also been fixing on the mute commands and are very close to making it work, aswell with unmute command.language feature is closing \nup on complete and about 70% of the bot has the language system working. We also made a new system that should be easier to use for bouth \nus devs and the translators.\n\n**All thats left for the release atm is:**\n-finishing synching \n-fixing the mute command and unmute command \n-make a functioning permissonlevel system\n-adding those last 30% of the bot that does not have the translationsystem in place. \n\nand the bot will have its huge release! *(about time if you asked me)*"
}
}';
$array = json_decode($string,1);
$message = $array['188762891137056769']['message'];
$re = '/\*\*(.*?)\*\*/m';
$subst = '<strong>$1</strong>';
echo preg_replace($re, $subst, $message);
?>
DEMO: https://3v4l.org/ovhGq
You used array inside str_replace("**","","$data") this is wrong, how you can fix it just replace $data with $emp
Your code is:
foreach ($data as $emp) {
echo str_replace("**","<strong>","$data"), $emp['message']."<br/>";
}
You see $data is an array, an $emp is the current element within the foreach loop.
So, you should do: str_replace("", "", $emp)
By the way, I see this: $emp['message'], which means $emp is an array too?
Maybe you should post the $readjson variable, so we'll know what type of data is.
If you want to enclose the text between ** with <strong></strong>, you need to use a regex. Here is a little code that does what you want :
function boldify($text) {
return preg_replace('/\*\*((.|\n|\r)*)\*\*/imU', '<strong>$1</strong>', $text);
}
Basically, it uses the function preg_replace to replace according to the regex (the first parameter).
How does this regex work :
1) You have \*\* at the beginning because that's your "opening tag". (* is a special regex character, so it needs escaping.)
2) You have ((.|\n|\r)*).
The inner part : .|\n|\r says "Catch me any character (the .) or (the |) a line feed (the \n) or a carriage return (the \r).".
Then you have the inner part enclosed with (inner part)*. This says "Match the inner part any number of time.".
Finally, you have the "middle part" enclosed with (middle part). This says "Remember what you just caught inside the parentheses, we will need it for the replace.
3) You have \*\* again.
4) All this is enclosed by /regex/imU.
The / are just there to say where the regex actually is.
The imU are flags: i is ignore case, m multiline, U ungreedy.
i are m are pretty straightforward, but U says "catch the smallest group possible".
As the second parameter you have '<strong>$1</strong>'. $1 is the group we remember from 2).
The third parameter is the subject.
I hope it was clear.
You can just use it like this :
echo boldify($emp['message']);

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.

PHP explode not working on string, fetched from EECMS template

I'm building an ExpressionEngine module in PHP.
In ExpressionEngine, one can access parameters passed to the module in a template using:
$my_param = $this->EE->TMPL->fetch_param('my_param');
However, when I fetch a string that way, explode does not work on it:
public function get_tyres()
{
$tyres = $this->EE->TMPL->fetch_param('tyres');
echo($tyres);
// this shows: '205/55R16M+S|205/55R16|205/55R16'
// now I want to split it into single tyres, using the pipe as a delimiter
$tyre_array = explode("|", $tyres);
foreach($tyre_array as $tyre)
{
echo($tyre . '<br>');
}
// the above produces: '205/55R16M+S|205/55R16|205/55R16',
// where I'd expect it to produce:
// 205/55R16M+S
// 205/55R16
// 205/55R16
}
I've tried to specifically cast to a string using $tyres = (string) $this->EE->TMPL->fetch_param('tyres');, with no luck.
I've also tried manually creating and exploding a string:
$tyres = '205/55R16M+S|205/55R16|205/55R16'; which worked, but obviously I need to get the param from the template, not hard code it.
Lastly, I tried using preg_split and a regex, with no luck either:
$tyre_array = preg_split('/\|/', $tyres); which also returned an array with the entire string in it.
What could be at work here? Is this a scope related thing? Is it an encoding-related thing? What to look for next?
Update
Okay, we're getting somewhere. I've added the following to the function:
for($i = 0; $i < strlen($tyres); $i++) {
echo substr($tyres, $i, 1) . ", ";
}
Which returns... {, v, e, r, s, i, o, n, :, t, y, r, e, s, }, and that is in fact the variable passed to PHP in the HTML template:
{exp:my_module:tyres tyres="{version:tyres}"}
<h1>{tyre:name}</h1>
... more irrelevant HTML
{/exp:my_module:tyres}
This means it has something to do with the parsing order of ExpressionEngine. Apparently, the variable {version:tyres} isn't parsed yet. So I pass that variable to the module, it tries to explode it by the pipe character, but the string {version:tyres} does not contain a pipe, meaning it can't be exploded. ExpressionEngine then returns {version:tyres} as a whole, passes it back in to the template and then the variable is parsed as 205/55R16M+S|205/55R16|205/55R16.
I've tested this, and can confirm that exploding by ':' returns the array:
array (size=2)
0 => string '{version' (length=8)
1 => string 'tyres}' (length=6)
I will now look in to ExpressionEngine parse order. If anyone has an idea on how to work around this, I'd be happy to know ;-).
I tested your code, copy and pasting your test string, and it works fine for me. Make sure your pipe ("|") is really the character you think it is, and not, say, some crazy unicode stuff that just looks like a pipe, but is actually Klingon for for 'staff', or something.
Try something like this as a reality check:
echo " the pipe is at " .strpos($tyres,"|"). " and I really hope this it says '12'";
The answer lies in the ExpressionEngine parse order, as outlined here: https://ellislab.com/expressionengine/user-guide/templates/template_engine.html#rendering-stages
Because the template tag {exp:my_module:tyres} used a variable passed to it by a template tag that it was nested in, the variable wasn't parsed yet as the innermost tags are parsed first.
Adding the parameter parse="inward" to the outer template tag makes ExpressionEngine parse that tag first, passing the correct variable to the inner template tag.
See https://ellislab.com/expressionengine/user-guide/templates/plugins.html#changing-parsing-order for more on changing the parsing 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).

Categories