I am trying to replace word or sequence of words in a string using preg_replace?
For example:
Change These:
ABCExample to abcExample
AnotherExample to anotherExample
XyzAbcExample to xyzAbcExample
Leave as it is:
xyzExample to xyzExample
new to new
You need to use preg_replace_callback function.
$str = <<<EOT
ABCExample
AnotherExample
XyzAbcExample
xyzExample
new
EOT;
echo preg_replace_callback('~(?m)^[A-Za-z]*?(?=(?:[A-Z][a-z]+)+$)~', function ($m)
{
return strtolower($m[0]);
}, $str);
I guess you are looking for str_ireplace.
This function returns a string or an array with all occurrences of
search in subject (ignoring case) replaced with the given replace
value. If you don't need fancy replacing rules, you should generally
use this function instead of preg_replace() with the i modifier.
Sample code (and a sample program):
$res1 = str_ireplace("abc", "xyz", "ABCExample to abcExample");
echo $res1;
Output: xyzExample to xyzExample
Related
I need to replace some text in a string. I think an example can explain better:
[myFile.json]
{ "Dear":"newString1", "an example string":"newString2" }
[example.php]
$myString = "#Dear# name, this is #an example string#.";
function gimmeNewVal($myVal){
$obj = json_decode(file_get_contents('myFile.json'));
return $obj->$myVal;
}
echo gimmeNewVal("Dear"); // This print "newString1"
So, what I need is to find any strings between the '#' symbol and for each string found I need to replace using the gimmeNewVal() function.
I already tried with preg_* functions but I'm not very able with regex...
Thanks for your help
You can use preg_match_all to match all strings of type #somestring# using regex #([^#]+)# and then iterate over a for loop to do the replacement of each such found string in the original string to replace with the actual value from your function gimmeNewVal which returns the value from your given json.
Here is the PHP code for same,
$myString = "#Dear# name, this is #an example string#.";
function gimmeNewVal($myVal){ // I've replaced your function from this to make it practically runnable so you can revert this function as posted in your post
$obj = json_decode('{ "Dear":"newString1", "an example string":"newString2" }');
return $obj->$myVal;
}
preg_match_all('/#([^#]+)#/', $myString, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
echo $matches[1][$i].' --> '.gimmeNewVal($matches[1][$i])."\n";
$myString = preg_replace('/'.$matches[0][$i].'/',gimmeNewVal($matches[1][$i]), $myString);
}
echo "\nTransformed myString: ".$myString;
Prints the transformed string,
Dear --> newString1
an example string --> newString2
Transformed myString: newString1 name, this is newString2.
Let me know if this is what you wanted.
You can use preg_replace_callback function
$myString = "#Dear# name, this is #an example string#.";
$obj = json_decode(file_get_contents('myFile.json'));
echo preg_replace_callback('/#([^#]+)#/',
function ($x) use($obj) { return isset($obj->{$x[1]}) ? $obj->{$x[1]} : ''; },
$myString);
demo
You can also use T-Regx tool:
pattern('#([^#])#')->replace($input)->all()->by()->map([
'#Dear#' => "newString1",
'#an example string#' => 'newString2'
]);
or
pattern('#([^#])#')->replace($input)->all()->group(1)->by()->map([
'Dear' => "newString1",
'an example string' => 'newString2'
]);
You can also use methods by()->map(), by()->mapIfExists() or by()->mapDefault(). Whatever you need :)
Let's say I have a the following string:
{{Hi}}, This {{is}} {{Debby}}.
I want to replace the text inside {{ANYTHING}} with variables passed to a function. For example, if the function is change_values('Hola', 'was', 'Antonio').
The result would be:
Hola, This was Antonio.
First word or character surrounded by {{}} was replaced by the first parameter of change_values(). Similarly, the second word or character was replaced by the second parameter and so on.
To be clear, the values Hi, is and Debby can change. The passed parameters can also change. The only thing that is consistent is that First {{}} would be replaced by first parameter and so on.
I was planning on using str_replace() originally but the text keepschanging each time. I also thought about using regex but cannot figure out how to do the replacements sequentially.
Any help would be appreciated.
A few more examples,
{{Fiona}} is a lucky {{girl}}.
will become
Mike is a lucky man.
I am using {{}} as identifiers in the original string to make it easy to figure out what needs to be replaced. If this can create an issue, I am open to other (better) solutions.
If you're using PHP5.6 or later, this function will do what you want. It uses ... to pack all the replacements into an array, and then preg_replace to replace all the strings surrounded by {{ and }} with the replacements. By using the limit parameter to preg_replace, we prevent the pattern replacing all the {{}} strings with the first value in the replacements array.
function change_values($string, ...$replacements) {
return preg_replace(array_fill(0, count($replacements), '/{{[^}]+}}/'), $replacements, $string, 1);
}
echo change_values('{{Hi}}, This {{is}} {{Debby}}.', 'Hola', 'was', 'Antonio');
echo change_values('{{Fiona}} is a lucky {{girl}}.', 'Mike', 'man');
Output:
Hola, This was Antonio.
Mike is a lucky man.
$input = '{{Fiona}} is a lucky {{girl}}.';
$replaceArray = ['Mike', 'man'];
$expectedOut = 'Mike is a lucky man.';
preg_match_all('/({{\w+}})/', $input,$matches);
$out = str_replace($matches[0], $replaceArray, $input);
if($out === $expectedOut){
print_r($out);
}
I have a little problem in PHP.
$string = "[:string] has [:int] [:string] and [:int] [:string]";
I just wanna modify (probably with str_replace) it with:
$string = "He has 5 apples and 3 bananas";
How could I do that?
(Classic str_replace() will modify all [:int] with the same word,
and is not what I want).
Thank you very much...
You could use the following regex, to capture all groups to replace and then iterate over it.
\[:([^\]]+)\]
Or you can just use preg_replace_callback and pass an desired replace function to it.
$data = [...];
preg_replace_callback('/\[:([^\]]+)\]/', $str, function (&$matches) use ($data) {
return doSomethingWithMatches..
});
$text = "
<tag>
<html>
HTML
</html>
</tag>
";
I want to replace all the text present inside the tags with htmlspecialchars(). I tried this:
$regex = '/<tag>(.*?)<\/tag>/s';
$code = preg_replace($regex,htmlspecialchars($regex),$text);
But it doesn't work.
I am getting the output as htmlspecialchars of the regex pattern. I want to replace it with htmlspecialchars of the data matching with the regex pattern.
what should i do?
You're replacing the match with the pattern itself, you're not using the back-references and the e-flag, but in this case, preg_replace_callback would be the way to go:
$code = preg_replace_callback($regex,'htmlspecialchars',$text);
This will pass the mathces groups to htmlspecialchars, and use its return value as replacement. The groups might be an array, in which case, you can try either:
function replaceCallback($matches)
{
if (is_array($matches))
{
$matches = implode ('', array_slice($matches, 1));//first element is full string
}
return htmlspecialchars($matches);
}
Or, if your PHP version permits it:
preg_replace_callback($expr, function($matches)
{
$return = '';
for ($i=1, $j = count($matches); $i<$j;$i++)
{//loop like this, skips first index, and allows for any number of groups
$return .= htmlspecialchars($matches[$i]);
}
return $return;
}, $text);
Try any of the above, until you find simething that works... incidentally, if all you want to remove is <tag> and </tag>, why not go for the much faster:
echo htmlspecialchars(str_replace(array('<tag>','</tag>'), '', $text));
That's just keeping it simple, and it'll almost certainly be faster, too.
See the quickest, easiest way in action here
If you want to isolate the actual contents as defined by your pattern, you could use preg_match($regex,$text,$hits);. This will give you an array of hits those bits that were between the paratheses in the pattern, starting at $hits[1], $hits[0] contains the whole matched string). You can then start manipulating these found matches, possibly using htmlspecialchars ... and combine them again into $code.
When I've a string:
$string = 'word1="abc.3" word2="xyz.3"';
How can I replace the point with a comma after xyz in xyz.3 and keep him after abc in abc.3?
You've provided an example but not a description of when the content should be modified and when it should be kept the same. The solution might be simply:
str_replace("xyz.", "xyz", $input);
But if you explicitly want a more explicit match, say requiring a digit after the ful stop, then:
preg_replace("/xyz\.([0-9])+/", 'xyz\${1}', $input);
(not tested)
something like (sorry i did this with javascript and didn't see the PHP tag).
var stringWithPoint = 'word1="abc.3" word2="xyz.3"';
var nopoint = stringWithPoint.replace('xyz.3', 'xyz3');
in php
$str = 'word1="abc.3" word2="xyz.3"';
echo str_replace('xyz.3', 'xyz3', $str);
You can use PHP's string functions to remove the point (.).
str_replace(".", "", $word2);
It depends what are the criteria for replace or not.
You could split string into parts (use explode or preg_split), then replace dot in some parts (eg. str_replace), next join them together (implode).
how about:
$string = 'word1="abc.3" word2="xyz.3"';
echo preg_replace('/\.([^.]+)$/', ',$1', $string);
output:
word1="abc.3" word2="xyz,3"