Replace characters with word in PHP? - php
Want to replace specific letters in a string to a full word.
I'm using:
function spec2hex($instr) {
for ($i=0; $i<strlen($instr); $i++) {
$char = substr($instr, $i,1);
if ($char == "a"){
$char = "hello";
}
$convString .= "&#".ord($char).";";
}
return $convString;
}
$myString = "adam";
$convertedString = spec2hex($myString);
echo $convertedString;
but that's returning:
hdhm
How do I do this? By the way, this is to replace punctuation with hex characters.
Thanks all.
Use http://php.net/substr_replace
substr_replace($instr, $word, $i,1);
ord() expects only a SINGLE character. You're passing in hello, so ord is doing its thing only on the h:
php > echo ord('hello');
104
php > echo ord('h');
104
So in effect your output is actually
hdhm
it you want to use your same code just change $convString .= "&#".ord($char).";";
to $convString .= $char;
If you just want to replace the occurrence of a with hello within the string you pass to the function, why not use PHP's str_replace()?
function spec2hex($instr) {
return str_replace("a","hello",$instr);
}
I must assume that you don't want to have hex characters instead of punctuation but html entities. Be aware that str_replace(), when called with arrays, will run over the string for multiple times, thus replacing the ";" in "{" also!
Your posted code is not useful for replacing punctuation.
use strtr() with arrays, it doesn't have the drawback of str_replace().
$aReplacements = array(',' => ',', '.' => '.'); //todo: complete the array
$sText = strtr($sText, $aReplacements);
Related
PHP Convert Unicode to text
I am receiving from a form the following urlencoded string %F0%9D%90%B4%F0%9D%91%99%F0%9D%91%92%F0%9D%91%97%F0%9D%91%8E%F0%9D%91%9B%F0%9D%91%91%F0%9D%91%9F%F0%9D%91%8E If I decode it I get the following formatted text: ๐ด๐๐๐๐๐๐๐๐ Is there any way with PHP to get the plain "Alejandra" text from the encoded or decoded string? I have tried without success several ways to do it with mb_convert_encoding($string, "UTF-16",mb_detect_encoding($string)) iconv('utf-16', 'utf-8', rawurldecode($string) and any other solution I could in stackoverflow. Edit: I tried the proposed solution $strAscii = iconv('UTF-8','ASCII//TRANSLIT',$str); but it deletes the special characters such as รกรฉรญรณรบรฑรง which we need to stay. Expected result input: ๐ด๐๐๐๐๐๐๐๐ output: Alejandra input: รlejandra output: รlejandra Thank you in advance.
urldecode or rawurldecode is sufficient. $string = "%F0%9D%90%B4%F0%9D%91%99%F0%9D%91%92%F0%9D%91%97%F0%9D%91%8E%F0%9D%91%9B%F0%9D%91%91%F0%9D%91%9F%F0%9D%91%8E"; $str = urldecode($string); var_dump($str); //string(36) "๐ด๐๐๐๐๐๐๐๐" Demo: https://3v4l.org/OMQ35 A special debugger gives me: string(36) UTF-8mb4. This means that there are also UTF-8 characters in the string that require 4 bytes. The character A is the Unicode character โ๐ดโ (U+1D434). Note: If the special UTF-8 characters cause problems, you can try to display the strings as ASCII characters with iconv. $strAscii = iconv('UTF-8','ASCII//TRANSLIT',$str); //string(9) "Alejandra"
What you are getting is called a "psuedo-alphabet", you can see a list of them here: https://qaz.wtf/u/convert.cgi. The one that you appear to be getting can be seen here: https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols Basically what you need to do is take the string, split it and use a lookup table to convert it back to regular characters. This implementation is terribly efficient but that's because I grabbed the alphabets from the above Wikipedia page and was too lazy to reorganise it. function math_symbols_to_plain_text($input, $alphabet) { $alphabets = [ ['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','๐ณ','๐ง','๐','๐','๐','๐ป','๐ฏ','๐','๐','๐ท','๐','๐ฃ','๐ซ'], ['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','๐','๐','๐','๐น','๐ญ','๐ก','๐','๐ต','๐ฉ','โจ','๐ ','๐','โค'] ]; $replace = ['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','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']; $lookup = [ 'serif-normal', 'serif-bold', 'serif-italic', 'serif-bolditalic', 'sans-normal', 'sans-bold', 'sans-italic', 'sans-bolditalic', 'script-normal', 'script-bold', 'franktur-normal', 'fraktur-bold', 'monospace', 'doublestruck' ]; $map_index = array_search($alphabet, $lookup); $split = mb_str_split($input); $output = ''; foreach ($split as $char) { foreach ($alphabets as $i => $letter) { if ($letter[$map_index] === $char) $output .= $replace[$i]; } } return $output; } $input = '๐ด๐๐๐๐๐๐๐๐'; $output = math_symbols_to_plain_text($input, 'serif-italic'); echo $input . PHP_EOL . $output . PHP_EOL; Yields: ๐ด๐๐๐๐๐๐๐๐ Alejandra
If I am not wrong, you are trying to decode URL then why you are not trying to use urldecode() follow this .PHP DOC
PHP new line every X characters in long characters sequence
How can I add a new line characters (\n\r) in txt file every 10 characters? What I have is a long sequence of characters, and I like to create a new line for each 10 characters. in example, let's say I have that sequence of characters: FadE4fh73d4F3fab5FnF4fbTKhuS591F60b55hsE and I like to convert it to that: FadE4fh73d 4F3fab5FnF 4fbTKhuS59 1F60b55hsE How can I do that ? I know that I can use a loop for that, but because the above string is an example and my string that I have to split it is really very very long, just I wander if there is any faster and more easy way to spit my string.
chunk_split($string, 10) http://php.net/manual/en/function.chunk-split.php for more info
using chunk_split(): $str = chunk_split($str, 10, "\n\r"); or using this regex: $str = preg_replace("/(.{10})/", "$1\n\r", $str); And by the way did you mean \r\n (New line in Windows environment) by \n\r? if so then the third argument for chunk_split() can be omitted.
<?php $foo = '01234567890123456789012345678901234567890123456789012345678901234567890123456789'; $result = chunk_split ($foo, 10, "\r\n"); echo $result; ?>
As mentioned above, the use of chunk_split() might have unwanted consequences, as the break sequence is always added to the end once again. You can instead use a combination of str_split() and implode() to first split the string every X characters and then recombine it with a break sequence. By using implode(), the break sequence will not be added to the end, again. I've build a helper function who does this for me after 75 chars: function createFold($s, $b = '\\n ') { $chunks = str_split($s, 75); return implode($b, $chunks); }
<b><</b>?<b>php</b><br/> $body=$row['details'];<br/> $str = chunk_split($body, 14, "<b><</b><b>br</b><b>/</b>");<br/> echo $str;<br/> ?
rtrim with underscore in php
I have line as 'Delux Room_room'. I want get 'Delux Room' as result. I tried following codes. Following code give following result. echo $row.'<br/>'; echo rtrim($row, 'room') .'<br/>'; echo rtrim($row, '_room') .'<br/>'; Result ;- Delux Room_room Delux Room_ Delux R But i want Delux Room. Please help me.
echo rtrim($row, '_room') .'<br/>'; That says "remove characters from the end of the string until you get to one that isn't _, r, o or m." Which obviously isn't what you mean. From the PHP manual: $charlist You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. You provide a list of characters, not a string you want to remove. You should probably use substr instead: echo substr($row, 0, -5); // remove the last 5 characers Another solution would be to use str_replace to replace unwanted substrings: echo str_replace('_room', '', $row); // replace "_room" with an empty string Note that this is less precise than the substr approach.
rtrim's second argument is a set of characters. You'll have to write your own method to remove a specific string instead: function rtrim_str($str, $trim) { if (substr($str, -strlen($trim)) == $trim) { return substr($str, 0, -strlen($trim)); } return $str; // String not present at end } echo rtrim_str($row, '_room');
Alternatively to #lonesomeday's solution, if your last past is of variable length: $pos = strrpos($row, '_'); echo $substr($row, 0, $pos);
You should use str_replace instead of rtrim, like this: echo $row.'<br/>'; echo str_replace('room', '', $row) .'<br/>'; echo str_replace('_room', '', $row) .'<br/>';
str_replace() on multibyte strings dangerous?
This question already has answers here: Can str_replace be safely used on a UTF-8 encoded string if it's only given valid UTF-8 encoded strings as arguments? (5 answers) Closed 10 hours ago. Given certain multibyte character sets, am I correct in assuming that the following doesn't do what it was intended to do? $string = str_replace('"', '\\"', $string); In particular, if the input was in a character set that might have a valid character like 0xbf5c, so an attacker can inject 0xbf22 to get 0xbf5c22, leaving a valid character followed by an unquoted double quote ("). Is there an easy way to mitigate this problem, or am I misunderstanding the issue in the first place? (In my case, the string is going into the value attribute of an HTML input tag: echo 'input type="text" value="' . $string . '">';) EDIT: For that matter, what about a function like preg_quote()? There's no charset argument for it, so it seems totally useless in this scenario. When you DON'T have the option of limiting charset to UTF-8 (yes, that'd be nice), it seems like you are really handicapped. What replace and quoting functions are available in that case?
No, youโre right: Using a singlebyte string function on a multibyte string can cause an unexpected result. Use the multibyte string functions instead, for example mb_ereg_replace or mb_split: $string = mb_ereg_replace('"', '\\"', $string); $string = implode('\\"', mb_split('"', $string)); Editย ย ย ย Hereโs a mb_replace implementation using the split-join variant: function mb_replace($search, $replace, $subject, &$count=0) { if (!is_array($search) && is_array($replace)) { return false; } if (is_array($subject)) { // call mb_replace for each single string in $subject foreach ($subject as &$string) { $string = &mb_replace($search, $replace, $string, $c); $count += $c; } } elseif (is_array($search)) { if (!is_array($replace)) { foreach ($search as &$string) { $subject = mb_replace($string, $replace, $subject, $c); $count += $c; } } else { $n = max(count($search), count($replace)); while ($n--) { $subject = mb_replace(current($search), current($replace), $subject, $c); $count += $c; next($search); next($replace); } } } else { $parts = mb_split(preg_quote($search), $subject); $count = count($parts)-1; $subject = implode($replace, $parts); } return $subject; } As regards the combination of parameters, this function should behave like the singlebyte str_replace.
The code is perfectly safe with sane multibyte-encodings like UTF-8 and EUC-TW, but dangerous with broken ones like Shift_JIS, GB*, etc. Rather than going through all the headache and overhead to be safe with these legacy encodings, I would recommend just supporting only UTF-8.
You could use either mb_ereg_replace by first specifying the charset with mb_regex_encoding(). Alternatively if you use UTF-8, you can use preg_replace with the u modifier.
How to get the last char of a string in PHP?
I need to get the last character of a string. Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?
substr("testers", -1); // returns "s" Or, for multibyte strings : mb_substr("multibyte stringโฆ", -1); // returns "โฆ"
substr($string, -1)
Or by direct string access: $string[strlen($string)-1]; Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions. As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];
From PHP 7.1 you can do this (Accepted rfc for negative string offsets): <?php $silly = 'Mary had a little lamb'; echo $silly[-20]; echo $silly{-6}; echo $silly[-3]; echo $silly[-15]; echo $silly[-13]; echo $silly[-1]; echo $silly[-4]; echo $silly{-10}; echo $silly[-4]; echo $silly[-8]; echo $silly{3}; // <-- this will be deprecated in PHP 7.4 die(); I'll let you guess the output. Also, I added this to xenonite's performance code with these results: substr() took 7.0334868431091seconds array access took 2.3111131191254seconds Direct string access (negative string offsets) took 1.7971360683441seconds
As of PHP 7.1.0, negative string offsets are also supported. So, if you keep up with the times, you can access the last character in the string like this: $str[-1] DEMO At the request of a #mickmackusa, I supplement my answer with possible ways of application: <?php $str='abcdef'; var_dump($str[-2]); // => string(1) "e" $str[-3]='.'; var_dump($str); // => string(6) "abc.ef" var_dump(isset($str[-4])); // => bool(true) var_dump(isset($str[-10])); // => bool(false)
I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest substr(trim($string), -1) EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear. trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first: $order = array("\r\n", "\n", "\r"); $string = str_replace($order, '', $string); $lastchar = substr($string, -1);
I'd advise to go for Gordon's solution as it is more performant than substr(): <?php $string = 'abcdef'; $repetitions = 10000000; echo "\n\n"; echo "----------------------------------\n"; echo $repetitions . " repetitions...\n"; echo "----------------------------------\n"; echo "\n\n"; $start = microtime(true); for($i=0; $i<$repetitions; $i++) $x = substr($string, -1); echo "substr() took " . (microtime(true) - $start) . "seconds\n"; $start = microtime(true); for($i=0; $i<$repetitions; $i++) $x = $string[strlen($string)-1]; echo "array access took " . (microtime(true) - $start) . "seconds\n"; die(); outputs something like ---------------------------------- 10000000 repetitions... ---------------------------------- substr() took 2.0285921096802seconds array access took 1.7474739551544seconds
As of PHP 8 you can now use str_ends_with() $string = 'testers'; if (\str_ends_with($string, 's') { // yes }
Remember, if you have a string which was read as a line from a text file using the fgets() function, you need to use substr($string, -3, 1) so that you get the actual character and not part of the CRLF (Carriage Return Line Feed). I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.
You can find last character using php many ways like substr() and mb_substr(). If youโre using multibyte character encodings like UTF-8, use mb_substr instead of substr Here i can show you both example: <?php echo substr("testers", -1); echo mb_substr("testers", -1); ?> LIVE DEMO
A string in different languages including C sharp and PHP is also considered an array of characters. Knowing that in theory array operations should be faster than string ones you could do, $foo = "bar"; $lastChar = strlen($foo) -1; echo $foo[$lastChar]; $firstChar = 0; echo $foo[$firstChar]; However, standard array functions like count(); will not work on a string.
Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);
Siemano, get only php files from selected directory: $dir = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project'; $files = scandir($dir, 1); foreach($files as $file){ $n = substr($file, -3); if($n == 'php'){ echo $file.'<br />'; } }