Viewed   91 times

How can I replace a certain part of my string with another one?

Input string:

"Hello, my name is Santa"

How can I change all a's in my string with something else?

I think I need a foreach loop, but I'm unsure how to use it.

 Answers

2
strtr ($str, array ('a' => '<replacement>'));

Or to answer your question more precisely:

strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
Saturday, August 13, 2022
1

Just do:

$row = str_replace("&", "&amp;", $row);

Note: Your foreach doesn't work because you need a reference, or use the key:

foreach ( $columns as &$value) { // reference
   $value  = str_replace("&", "&amp;", $value);
}
unset($value); // break the reference with the last element

Or:

foreach ($columns as $key => $value){
   $columns[$key]  = str_replace("&", "&amp;", $value);
}

Although it is not necessary here because str_replace accepts and returns arrays.

Sunday, August 7, 2022
 
4

The bug is in str.replace(start_pos, end_pos, to);

From the std::string doc at http://www.cplusplus.com/reference/string/string/replace/

string& replace ( size_t pos1, size_t n1,   const string& str );

You are using an end-position, while the function expects a length.

So change to:

while((start_pos = str.find(from, start_pos)) != std::string::npos) {
         str.replace(start_pos, from.length(), to);
         start_pos += to.length(); // ...
}

Note: untested.

Monday, September 19, 2022
 
nvirth
 
3

If you aren't required to use PHP, I would highly recommend performing stuff like this from the command line. It's by far the best tool for the job, and much easier to use.

In any case, the sed (Stream Editor) command is what you are looking for:

sed s/search/replace oldfilename > newfilename

If you need case-insensitivity:

sed s/search/replace/i oldfilename > newfilename

If you need this to perform dynamically within PHP, you can use passthru():

$output = passthru("sed s/$search/$replace $oldfilename > $newfilename");
Tuesday, November 8, 2022
5

You don't even need to use substring or replace, you can use this:

SELECT 'test' + RIGHT(email, charindex('@', REVERSE(email)))
FROM YourTable

You can test it out with this:

DECLARE @email nvarchar(50)
SET @email = 'carmine32@hotmail.com'
PRINT 'test' + RIGHT(@email, charindex('@', REVERSE(@email)))
Wednesday, August 17, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :