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.
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.
Just do:
$row = str_replace("&", "&", $row);
Note: Your foreach doesn't work because you need a reference, or use the key:
foreach ( $columns as &$value) { // reference
$value = str_replace("&", "&", $value);
}
unset($value); // break the reference with the last element
Or:
foreach ($columns as $key => $value){
$columns[$key] = str_replace("&", "&", $value);
}
Although it is not necessary here because str_replace
accepts and returns arrays.
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.
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");
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)))
Or to answer your question more precisely: