Is there anything similar in Python like PHP's str_replace function?
I am looking for something to do this:
string_world = str_replace('Place', "World", "Hello World!")
print (string_world)
Hello Peter!
Specifically something to replace my
str_replace('mp', ' ', $_GET['FML'])
First thing when you are printing "Hello Peter" You should write string_world = str_replace("World", "Peter", "Hello World!") Please check your question.
For String replace in Python, use something like this:
str = "Hello World"
print str.replace("World", "Peter")
print str.replace("World", "Peter", 1) #Parameters: str.replace(find, replace, count)
You can use .replace() on string:
str = "Hello World!"
print str.replace("World", "Place")
Related
I have a data base with texts and in each text there are words (tags) that start with # (example of a record : "Hi I'm posting an #issue on #Stackoverflow ")
I'm trying to find a solution to add html code to transform each tag into a link when printing the text.
So the text are stored as strings in MySQL database like this :
Some text #tag1 text #tag2 ...
I want to replace all these #abcd with
#abcd
And have a final result as follow:
Some text #tag1 text #tag2 ...
I guess that i should use some regex but it is not at all my strong side.
Try the following using preg_replace(..)
$input = "Hi I'm posting an #issue on #Stackoverflow";
echo preg_replace("/#([a-zA-Z0-9]+)/", "<a href='targetpage.php?val=$1'>#$1</a>", $input);
http://php.net/manual/en/function.preg-replace.php
A simple solution could look like this:
$re = '/\S*#(\[[^\]]+\]|\S+)/m';
$str = 'Some text #tag1 text #tag2 ...';
$subst = '#$1';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Demo
If you are actually after Twitter hashtags and want to go crazy take a look here how it is done in Java.
There is also a JavaScript Twitter library that makes things very easy.
Try this the function
<?php
$demoString1 = "THIS is #test STRING WITH #abcd";
$demoString2 = "Hi I'm posting an #issue on #Stackoverflow";
function wrapWithAnchor($link,$string){
$pattern = "/#([a-zA-Z0-9]+)/";
$replace_with = '<a href="'.$link.'?val=$1">$1<a>';
return preg_replace( $pattern, $replace_with ,$string );
}
$link= 'http://www.targetpage.php';
echo wrapWithAnchor($link,$demoString1);
echo '<hr />';
echo wrapWithAnchor($link,$demoString2);
?>
I am trying to work on a script but I am stuck in one place.
Eg. To get a php output I have used..
str_php = """
<?php
echo "Hello World!";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
Ok, so I get the output as it is....
<?php
echo "Hello World!";
?>
So my php code is running. all good till here. But, the problem starts from when I try using "\" and "\n" and "\r"
str_php = """
<?php
echo "Hello World!"; \n echo "How are you"; \n echo "God bless you";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
But here I dont get the output as it is.
<?php
echo "Hello World!";
echo "How are you";
echo "God bless you";
?>
And the "\" it just vanishes... at an output.
Eg. I want an output of a php hyperlink something like...
str_php = """<?php
print("$dirArray[$index]");
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
and the output I get is...
<?php
print("$dirArray[$index]");
?>
The "\" is missing and the php does not run creating error.
print("$dirArray[$index]") - Original
print("$dirArray[$index]") - python output
Can any one help me out with "\", "\n", "\r" ??
Just use "\" to escape the "\" character.
Since it is common to want to have long strings containing several "\", Python also allows one
to prefix the string opening quotes if ar r (for "raw") - inside such
a string, no escaping of "\n" to chr(10) or "\t" to chr(9) happens:
>>> print (r"Hello \n world!")
Hello \n world!
You need to escape your "\" with another backslash writting it as "\\".
If you use "\n" it will be parsed and make a newline. Try to use '\n', strings enclosed in '\n' are not parsed and it should print out as you want it to.
I am trying to replace multiple variables in a text.
I have For example this text:
This is an example text , my variables are:
%name%
%frontname%
%lastname%
%email%
No I want to replace each variable that is between the % % characters with {$variable}.
So my output looks like this:
This is an example text , my variables are:
{$name}
{$frontname}
{$lastname}
{$email}
The pattern I am trying to use is this :
$textResponder = preg_replace('#\%[^\%]+\%#', '{$$1}', $text);
But that is not working, as I get this as output: {$} {$} {$}. Does somebody know what the correct pattern would be?
Thanks in advance
$var = "Hello, %test% World %another test%!";
echo preg_replace('#%(.*?)%#', '{\$$1}', $var);
Test here
Try
preg_replace('/%(.*?)%/', '{\$$1}', $text);
#Gert Van de Ven You need to escape the dollar's special meaning:
$var = "Hello, %test% World!";
echo preg_replace('#\%(.*?)\%#', '{\$$1}', $var);
I've got a string containing values such as "hello world\' hello world\'" and I'd like to get rid of the escape characters (the backslashes.)
I've tried the following code:
str_replace("\\", "", $data);
But it doesn't seem to work.
If all you want to do is to get rid of backslashes, then there's a very handy PHP function that accomplishes just that
$var = stripslashes($var);
Assuming you're using $var as the last parameter in str_replace() instead of $data, it should work fine.
$var = "hello world\' hello world\'";
echo $var . "<br />";
echo str_replace("\\", "", $var) . "<br />";
Output:
hello world\' hello world\'
hello world' hello world'
this should work great for you you were not referencing the variable $var correctly in php replace subject parameter also assuming you need to replace the \' you were putting \ which searches for it hence nothing was found to be replaced hope this helps
$var = "hello world\' hello world\'";
echo str_replace("\'","",$var);
I have code like this:
<?php
echo '<script type="text/javascript">';
echo 'var out="'.$txt.'";';
echo '</script>';
?>
Where $txt is a PHP variable that can contain newlines like this:
line1
line2 hello world
Which would end up like this:
var out="line1
line2 hello world";
Which will cause a Javascript error, of course.
What is the best way to handle this? The out variable will be used in a HTML textarea, so I don't think it can be parsed into <br>
$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );
should replace newlines. Don't do it this way.
This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:
$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";
json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.
you can add a \ at the end of a line to create a multi line String
var out="line1 \
line2 hello world";
Most of these don't work for me.
Normally, I'd use json_encode like
<?php
$MyVar = json_encode($MyVar);
?>
<javascript language='javascript'>
MyVar = <?php echo $MyVar; ?>
But for a quick fix you can just break a line like this:
Pay attention to the double quotes.
<?php
$MyVar = "line one here
then line two here
finally line five here";
//** OR
$MyVar = $MyVarA .
"
"
. $MyVarB;
?>
<HTML>
<HEAD>
<javascript language='javascript'>
Myvar = "<?php echo $MyVar; ?>";
. . .
You can use str_replace to convert line breaks into a different character (in this case, perhaps a space, but it depends how you want the output to show up)
$out = str_replace("\n", '\n', $in);
$content = str_replace( "\\n", "\\\\\\n", $content );
Result:
var a = "Hello \
World"
I tried this and it worked well.
<?php
echo '<script type="text/javascript">';
$txt = "line1 \\n line2 hello world";
echo 'var out="'.$txt.'";';
echo '</script>';
?>
I am using PHP 5.3