I have a string with question marks ('?') in it and I want to replace it with something parsable.
However str_replace will not replace any ? characters in my string...
$str = str_replace('?', 'replacement', $str);
Any ideas?
That code does replace question marks with the word replacement, which means that's not the code you're using, or what's in your string is not a question mark.
PHP's string functions only operate correctly on latin1 (iso-8859-1) encoded strings. In many encodings there may be many codepoints that correspond to a glyph that looks like a question mark visually, but is not the same as ASCII ?.
$str = "Hello? Anyone home?";
$str = str_replace('?', 'replacement', $str);
echo $str;
Output:
Helloreplacement Anyone homereplacement
This will replace ? in to space. This may help you.
<?php
$str = "this ? does ? indeed ? work";
$char='';
$str1 = str_replace('?',$char,$str);
echo $str1;
?>
Related
Good afternoon,
I have an error in my preg_replace. I would like to replace && with only one &, and ?& with ?.
My code looks like this:
$reg = preg_replace("#\&\&#is", "&
", $reg);
$reg = preg_replace("#\?\&#is", "?
", $reg);
Could you please help me fix this? I am sure, it some basic error, so sorry for that...
Thanks!
You do not need to escape & only the ?
$reg = preg_replace("#&&#", "&", $reg);
$reg = preg_replace("#\?&#", "?", $reg);
You can simplify the two regexs into one.
echo preg_replace("#([?&])\s*&#", "$1", ' ? &lang=en');
Output:
?lang=en
Your modifiers didn't make sense since you aren't using alpha characters or the ..
Also & isn't a special regex character, just ?. If in a character class ([]) neither will need to be replaced.
Regex101 Demo: https://regex101.com/r/iS4mQ0/1
There is an old question from 2011 but with a wrong answer.
Maybe now someone can give a better answer. The question was: How can we replace the backslashes with forward slashes from this variable-link:
$str = "http://www.domain.com/data/images\flags/en.gif";
The wrong answer was that:
echo $str = str_replace('\\', '/', $str);
And it was wrong because the result of that code changes the content of the link. (http://www.domain.com/data/imageslags/en.gif)
It finds not only the backslash but the letter f after that and it deletes them because \f means "formfeed (hex 0C)". So how can we avoid this wrong replacement?
The Code is here
i hope this helps you
$str = "http://www.domain.com/data/images\flags/en.gif";
echo $str = str_replace('lags', "/flags", $str);
You can use addcslashes but you'll have to specify each possible escaped character that could occur in $str
$str = "http://www.domain.com/data/images\flags/en.gif";
$escaped = str_replace("\\","/",addcslashes($str,"\f\r\n\t"));
echo $escaped; // result is 'http://www.domain.com/data/images/flags/en.gif'
I need delete all tags from string and make it without spaces.
I have string
"<span class="left_corner"> </span><span class="text">Adv</span><span class="right_corner"> </span>"
After using strip_tags I get string
" Adv "
Using trim function I can`t delete spaces.
JSON string looks like "\u00a0...\u00a0".
Help me please delete this spaces.
Solution of this problem
$str = trim($str, chr(0xC2).chr(0xA0))
You should use preg_replace(), to make it in multibyte-safe way.
$str = preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', $str);
Notes:
this will fix initial #Андрей-Сердюк's problem: it will trim \u00a0, because \s matches Unicode non-breaking spaces too
/u modifier (PCRE_UTF8) tells PCRE to handle subject as UTF8-string
\x00 matches null-byte characters to mimic default trim() function behavior
Accepted #Андрей-Сердюк trim() answer will mess with multibyte strings.
Example:
// This works:
echo trim(' Hello ', ' '.chr(0xC2).chr(0xA0));
// > "Hello"
// And this doesn't work:
echo trim(' Solidarietà ', ' '.chr(0xC2).chr(0xA0));
// > "Solidariet?" -- invalid UTF8 character sequense
// This works for both single-byte and multi-byte sequenses:
echo preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', ' Hello ');
// > "Hello"
echo preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', ' Solidarietà ');
// > "Solidarietà"
How about:
$string = '" Adv "';
$noSpace = preg_replace('/\s/', '', $string);
?
http://php.net/manual/en/function.preg-replace.php
I was using the accepted solution for years and I've been wrong all this time. If I can find this solution in 2022, others too, so please change the accepted solution to the one from #e1v who was right all this time.
You SHOULD NOT DO THIS!
echo trim('Au delà', ' '.chr(0xC2).chr(0xA0));
As it corrupts the UTF-8 encoding:
Au del�
Note that a "modern" (PHP 7) way to write this could be:
echo trim('Au delà', " \u{a0}");//This is WRONG, don't do it!
Personally, when I have to deal with non breakable spaces (Unicode 00A0, UTF8 C2A0) in strings, I replace the trailing/ending ones by regular spaces (Unicode 0020, UTF8 20), and then trim the string. Like this:
echo trim(preg_replace('/^\s+|\s+$/u', ' ', "Au delà\u{a0}"));
(I would have post a comment or just vote the answer up, but I can't).
$str = '<span class="left_corner"> </span><span class="text">Adv</span><span class="right_corner"> </span>';
$rgx = '#(<[^>]+>)|(\s+)#';
$cleaned_str = preg_replace( $rgx, '' , $str );
echo '['. $cleaned_str .']';
So this is a preg_replace associated question i guess,
I have a string with multiple repeating patterns
they all formated as:
some string :22: more text :12: etc
how do i replace the ":" around them with some different char?
You can do something like this:
$string = 'some string :22: more text :12: etc';
$regex = '/:(\d+):/';
$newString = preg_replace($regex, "#$1#", $string);
Note: You have to replace the '#' in the second parameter with the char you want (also different chars before and after the numbers).
Sbustitudes _ for : around numbers:
preg_replace('/:(\d+):/', '_$1_', 'some string :22: more text :12: etc');
EDIT: Misunderstood original question. However, is still a flexible option:
$result = str_replace(":22:", "tag", "some string :22: more text :12: etc");
$result = str_replace(":12:", "other_tag", $result);
Replace the ? character with your replacement character.
I am applying the following function
<?php
function replaceChar($string){
$new_string = preg_replace("/[^a-zA-Z0-9\sçéèêëñòóôõöàáâäåìíîïùúûüýÿ]/", "", $string);
return $new_string;
}
$string = "This is some text and numbers 12345 and symbols !£%^#&$ and foreign letters éèêëñòóôõöàáâäåìíîïùúûüýÿ";
echo replaceChar($string);
?>
which works fine but if I add ã to the preg_replace like
$new_string = preg_replace("/[^a-zA-Z0-9\sçéèêëñòóôõöàáâãäåìíîïùúûüýÿ]/", "", $string);
$string = "This is some text and numbers 12345 and symbols !£%^#&$ and foreign letters éèêëñòóôõöàáâäåìíîïùúûüýÿã";
It conflicts with the pound sign £ and replaces the pound sign with the unidentified question mark in black square.
This is not critical but does anyone know why this is?
Thank you,
Barry
UPDATE: Thank you all. Changed functions adding the u modifier: pt2.php.net/manual/en/… – as suggested by Artefacto and works a treat
function replaceChar($string){
$new_string = preg_replace("/[^a-zA-Z0-9\sçéèêëñòóôõøöàáâãäåìíîïùúûüýÿ]/u", "", $string);
return $new_string;
}
If your string is in UTF-8, you must add the u modifier to the regex. Like this:
function replaceChar($string){
$new_string = preg_replace("/[^a-zA-Z0-9\sçéèêëñòóôõöàáâäåìíîïùúûüýÿ]/u", "", $string);
return $new_string;
}
$string = "This is some text and numbers 12345 and symbols !£%^#&$ and foreign letters éèêëñòóôõöàáâäåìíîïùúûüýÿ";
echo replaceChar($string);
Chances are that your string is UTF-8, but preg_replace() is working on bytes
that code is valid ...
maybe you should try Central-European character encoding
<?php
header ('Content-type: text/html; charset=ISO-8859-2');
?>
You might want to take a look at mb_ereg_replace(). As Mark mentioned preg_replace only works on byte level and does not work well with multibyte character encodings.
Cheers,
Fabian