This question already has answers here:
Replace character's position in a string
(4 answers)
Closed 3 years ago.
The code is in below.I have a string.i want to replace a specific character with its fixed position.
$string = 'syeds nomasn shibsly';
$char = 't';
$position = [0,4,10];
foreach($position as $pos) {
$str = substr_replace($string, $char, $pos);
}
echo $str;
Output will be tyedt nomatn shibsly
Hope you got my problem. Please help me.
You can access the individual characters of strings like an array:
foreach ($position as $pos) {
$string[$pos] = $char;
}
Your original code works fine with a couple of modifications.
You're not updating $string inside the loop, so your $str variable will end up with only the final position changed, since each iteration looks at the original string. You also need to pass in the length parameter to substr_replace, so that the correct portion of the string is replaced.
Try changing the code to:
foreach ($position as $pos) {
$string = substr_replace($string, $char, $pos, 1);
}
echo $string;
tyedt nomatn shibsly
See https://eval.in/968698
(You also need to fix the array syntax to use square brackets)
Related
This question already has answers here:
Extracting all values between curly braces regex php
(3 answers)
Closed 3 years ago.
so I have this email template that consist of something of a template strings
<p>My name is {name}</p>
that later on, when I trigger email function, I can just do file_get_contents and use str_replace to replace that part with the correct value
$temp = file_get_contents(__DIR__.'/template/advertise.html');
$temp = str_replace('{img}','mysite.com/assets/img/face.jpg',$temp);
Now what wanted this time is to get those word inside {} and append to an array $words = [];
What I've tried is using explode technique e.g.
$word = 'Hello {img}, age {age}, I live in {address}';
$word = explode('}',$word);
$words = [];
foreach( $word as $w ){
$words[] = explode('{',$w)[1];
}
print_r($words);
but is there other better way to do this? any ideas, help?
Try the following:
$word = 'Hello {img}, age {age}, I live in {address}';
if (preg_match_all('/\{([^\}]+)\}/', $word, $matches, PREG_PATTERN_ORDER)) {
var_dump($matches[1]);
}
It should return all the variable names inside the curly braces.
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 3 years ago.
I need someone who can make the following output which is a single string
[{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}]1
to
{"mobile":"XXX-XXX-XXXX",
"permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}",
"tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}
Help me removing first '[' and last ']1' in the above string. Thanks in advance
This should work for you.
$final_str = rtrim(ltrim($your_str, '['), ']1');
Try below code,
<?php
$str = '[{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}]1';
$temp_str = preg_replace('/\[/',"",$str);
$new_str = str_replace("]1","",$temp_str);
echo $new_str;
?>
Output,
{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}
This will remove first and last character from your string
$result = substr($string, 1, -2);
Here is the link if you want to explore more:
https://www.w3schools.com/php/func_string_substr.asp
Try ltrim() and rtrim()
$str = '[{"mobile":"XXX-XXX-XXXX","permaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}","tempaddress":"{\"country\":\"country\",\"state\":\"state\",\"city\":\"city\",\"street\":\"street\"}"}]1';
$getTrim = ltrim($str, '[');
$getTrim = rtrim($getTrim, ']1');
echo $getTrim;
OR
$getTrim = rtrim(ltrim($str, '['), ']1');
you can use str_replace or preg_replace replace your keyword with empty string.
This question already has answers here:
How to strip trailing zeros in PHP
(15 answers)
Closed 7 years ago.
I have a string like this:
14522354265300000000000
I want to display it without zero values, how I can do this? I do this
$pos = strpos($route, '0');
$length = count(str_split($route));
$a = $length - $pos;
$a = substr($route, 0, $a);
but it remove 3 in the end of string. Can somebody help me?
Additional:
If string will be 123088888880, I want make it 123.
You can use rtrim for this:
echo rtrim("14522354265300000000000", "0"); // outputs: 145223542653
here's a nice algo:
<?php
$string = "14522354265300000000000";
$new_string = '';
for($i=0; $i<strlen($string) ; $i++){
if($string[$i] != '0'){
$new_string .= $string[$i];
}
}
echo $new_string;
?>
rtrim is only if you have zero's at end of string :)
You can use rtrim('14522354265300000000000', '0')
Assuming I have a string
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
there are three 1024, I want to replace the third with JJJJ, like this :
output :
0000,1023,1024,1025,1024,1023,1027,1025,JJJJ,1025,0000
how to make str_replace can do it
thanks for the help
As your question asks, you want to use str_replace to do this. It's probably not the best option, but here's what you do using that function. Assuming you have no other instances of "JJJJ" throughout the string, you could do this:
$str = "0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
$str = str_replace('1024','JJJJ',$str,3)
$str = str_replace('JJJJ','1024',$str,2);
Here is what I would do and it should work regardless of values in $str:
function replace_str($str,$search,$replace,$num) {
$pieces = explode(',',$str);
$counter = 0;
foreach($pieces as $key=>$val) {
if($val == $search) {
$counter++;
if($counter == $num) {
$pieces[$key] = $replace;
}
}
}
return implode(',',$pieces);
}
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
echo replace_str($str, '1024', 'JJJJ', 3);
I think this is what you are asking in your comment:
function replace_element($str,$search,$replace,$num) {
$num = $num - 1;
$pieces = explode(',',$str);
if($pieces[$num] == $search) {
$pieces[$num] = $replace;
}
return implode(',',$pieces);
}
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
echo replace_element($str,'1024','JJJJ',9);
strpos has an offset, detailed here: http://php.net/manual/en/function.strrpos.php
So you want to do the following:
1) strpos with 1024, keep the offset
2) strpos with 1024 starting at offset+1, keep newoffset
3) strpos with 1024 starting at newoffset+1, keep thirdoffset
4) finally, we can use substr to do the replacement - get the string leading up to the third instance of 1024, concatenate it to what you want to replace it with, then get the substr of the rest of the string afterwards and concatenate it to that. http://www.php.net/manual/en/function.substr.php
You can either use strpos() three times to get the position of the third 1024 in your string and then replace it, or you could write a regex to use with preg_replace() that matches the third 1024.
if you want to find the last occurence of your string you can used strrpos
Do it like this:
$newstring = substr_replace($str,'JJJJ', strrpos($str, '1024'), strlen('1024') );
See working demo
Here's a solution with less calls to one and the same function and without having to explode, iterate over the array and implode again.
// replace the first three occurrences
$replaced = str_replace('1024', 'JJJJ', $str, 3);
// now replace the firs two, which you wanted to keep
$final = str_replace('JJJJ', '1024', $replaced, 2);
I have a script that generates content containing certain tokens, and I need to replace each occurrence of a token, with different content resulting from a separate loop.
It's simple to use str_replace to replace all occurrences of the token with the same content, but I need to replace each occurrence with the next result of the loop.
I did see this answer: Search and replace multiple values with multiple/different values in PHP5?
however it is working from pre-defined arrays, which I don't have.
Sample content:
This is an example of %%token%% that might contain multiple instances of a particular
%%token%%, that need to each be replaced with a different piece of %%token%% generated
elsewhere.
I need to replace each occurrence of %%token%% with content generated, for argument's sake, by this simple loop:
for($i=0;$i<3;$i++){
$token = rand(100,10000);
}
So replace each %%token%% with a different random number value $token.
Is this something simple that I'm just not seeing?
Thanks!
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);
}
I know this is an old thread, but I stumbled across it while trying to achieve something similar. If anyone else sees this, I think this is a little nicer:
Create some sample text:
$text="This is an example of %%token%% that might contain multiple instances of a particular
%%token%%, that need to each be replaced with a different piece of %%token%% generated
elsewhere.";
Find the search string with regex:
$new_text = preg_replace_callback("|%%token%%|", "_rand_preg_call", $text);
Define a callback function to change the matches
function _rand_preg_call($matches){
return rand(100,10000);
}
Echo the results:
echo $new_text;
So as a function set:
function _preg_replace_rand($text,$pattern){
return preg_replace_callback("|$pattern|", "_rand_preg_call", $text);
}
function _rand_preg_call($matches){
return rand(100,10000);
}
I had a similar issue where I had a file that I needed to read. It had multiple occurrences of a token, and I needed to replace each occurrence with a different value from an array.
This function will replace each occurrence of the "token"/"needle" found in the "haystack" and will replace it with a value from an indexed array.
function mostr_replace($needle, $haystack, $replacementArray, $needle_position = 0, $offset = 0)
{
$counter = 0;
while (substr_count($haystack, $needle)) {
$needle_position = strpos($haystack, $needle, $offset);
if ($needle_position + strlen($needle) > strlen($haystack)) {
break;
}
$haystack = substr_replace($haystack, $replacementArray[$counter], $needle_position, strlen($needle));
$offset = $needle_position + strlen($needle);
$counter++;
}
return $haystack;
}
By the way, 'mostr_replace' is short for "Multiple Occurrence String Replace".
You can use the following code:
$content = "This is an example of %%token%% that might contain multiple instances of a particular %%token%%, that need to each be replaced with a different piece of %%token%% generated elsewhere.";
while (true)
{
$needle = "%%token%%";
$pos = strpos($content, $needle);
$token = rand(100, 10000);
if ($pos === false)
{
break;
}
else
{
$content = substr($content, 0,
$pos).$token.substr($content, $pos + strlen($token) + 1);
}
}