Asked  7 Months ago    Answers:  5   Viewed   39 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

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

Or to answer your question more precisely:

strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));
Wednesday, March 31, 2021
 
Zach
answered 7 Months ago
33

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)

Wednesday, March 31, 2021
 
axiomer
answered 7 Months ago
18

I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself.

It looks to me like this problem works well with explode(). So, using the example token generator you provided, the solution looks like this:

$shrapnel = explode('%%token%%', $str);
$newStr = '';
for ($i = 0; $i < count($shrapnel); ++$i)  {
    // The last piece of the string has no token after it, so we special-case it
    if ($i == count($shrapnel) - 1)
        $newStr .= $shrapnel[$i];
    else
        $newStr .= $shrapnel[$i] . rand(100,10000);
}
Wednesday, March 31, 2021
 
clean_coding
answered 7 Months ago
77

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.

Sunday, June 13, 2021
 
Corsair
answered 5 Months ago
70

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)))
Thursday, August 12, 2021
 
Grzegorz
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share