i want to replace a char and want to put that character just after next char in php.
for example:
<?php
$exa = array("R" => "r", "A" => "a", "V" => "v", "I" => "i");
echo strtr("RAVI", $exa);
?> //displays "ravi" ok
i want to replace "V" with "v" and then want to put it after "I".
like this: "raiv"
I think this solution might interest you:
Function
function replaceAndMove($text, $replacements) {
$from = array_keys($replacements);
$to = array_values($replacements);
function fixFrom($s) {
return '/' . preg_quote($s, '/') . '(.|$)' . '/';
}
function fixTo($s) {
return '${1}' . $s;
}
$from_ready = array_map('fixFrom', $from);
$to_ready = array_map('fixTo', $to);
return preg_replace($from_ready, $to_ready, $text);
}
Test Case
$text = "abcdXefghXijklX----aFb~~~cMd";
$replacements = array(
'X' => 'x',
'F' => 'f',
'M' => 'm',
);
echo $text . '<br>';
echo replaceAndMove($text, $replacements);
Output
abcdXefghXijklX----aFb~~~cMd
abcdexfghixjkl-x---abf~~~cdm
Edit: Fixed problems with regex-special chars, such as . or ]
do the str_replace first, then use strlen, substr and the index of the character string to replace the last 2 spots if that is what you are trying to do. Because you can access a string like an array each characters $t[1] == e if the string was "test"
If you have a few "set" patterns you could just do this:
$find = array('RAVI',...,so on);
$replace = array('raiv',..., so on);
$input = 'RAVI';
echo str_replace($find, $replace, $input);
Just add more set pairs to the arrays for more replacements... If that's all you want.
Are you looking for something like this:
<?php
$string = "RAVIVL";
$replace_char = "v";
$string = strtolower($string);
$pos = array_keys(array_intersect(str_split($string),array($replace_char)));
foreach ($pos as $p) {
if (isset($string[$p+1])) {
$string[$p] = $string[$p+1];
$string[$p+1] = $replace_char;
}
}
echo $string;
?>
Swaps all occurrences o "v" with the following letter.
Related
I am trying to check if word is occur in a string but not to be the first and last word, if its true then remove the space after and before of the word and replace with a underscore.
Input:
$str = 'This is a cool area";
Output:
$str = 'This is a_cool_area";
I want to check that the word 'cool' is inside the string but not a first and last word. if yes the remove the space & replace with '_'
You can use preg_replace to do this job, using this regex:
/(?<=\w)\s+(' . $word . ')\s+(?=\w)/i
which looks for the word, surrounded by at least one word character on either side (to prevent matching at the beginning or ending of the sentence). Usage in PHP:
$str = 'This is a cool area';
$word = 'cool';
$str = preg_replace('/(?<=\w)\s+(' . $word . ')\s+(?=\w)/i', '_$1_', $str);
echo $str . "\n";
$str = ' Cool areas are cool ';
$str = preg_replace('/(?<=\w)\s+(' . $word . ')\s+(?=\w)/i', '_$1_', $str);
echo $str . "\n";
Output:
This is a_cool_area
Cool areas are cool
Demo on 3v4l.org
function checkWord($str, $word)
{
$arr = explode(" ", $str);
$newArr = array_slice($arr, 1, -1);
$key = array_search($word, $newArr);
if($key !== false)
{
return implode('_',array_slice($arr, $key, 3));
}
else
{
return $str;
}
}
echo checkWord('This is a cool area', 'cool');
I want to insert a character inside a word in a string if a word match is found while keeping the case. This code works fine but I have to specify the resulting word.
$string = "Quick brown fOx jumps right over the lazy dog.";
$swears = array(
"BROWN" => "BRO.WN",
"fox" => "f.ox",
"Dog" => "D.og",
);
$filtered = str_ireplace(array_keys($swears), array_values($swears), $string);
The problem with this code is any "brown" becomes BRO.WN
Is it possible to insert a character if the word matches. Like Brown becomes Bro.wn; brown becomes bro.wn while keeping the case.
There are probably much better ways to do that, but here is the only answer I came up with :
foreach($swears as $swear => $modified_swear) {
$swear_pos = stripos($string, $swear);
if($swear_pos !== false) {
$swear_len = strlen($swear);
if($swear_len >= 3) {
$new_string = substr($string, 0, $swear_pos);
$new_string .= substr($string, $swear_pos, $swear_len-2);
$new_string .= '.';
$new_string .= substr($string, $swear_pos+($swear_len-2));
$string = $new_string;
}
}
}
This code works only if you actually was trying to add a single dot before the two last characters of a swear.
EDIT :
New code that can modify all occurences of a list of words.
$searched_pattern = '/\b(?:';
foreach($swears as $swear => $modified_swear) {
$searched_pattern .= '('.$swear.')|';
}
$searched_pattern = rtrim($searched_pattern, '|');
$searched_pattern .= ')\b/i';
$string = preg_replace_callback(
$searched_pattern,
function($matches) {
$word = $matches[0];
$swear_len = strlen($word);
if($swear_len >= 3) {
$new_word .= substr($word, 0, $swear_len-2);
$new_word .= '.';
$new_word .= substr($word, $swear_len-2);
$word = $new_word;
}
return $word;
},
$string
);
I'm not exactly clear what you want?
There are alternatives for this test. Then do a str_replace inserting a char into a specific position.
<?php
$string = "Quick brown fOx jumps right over the lazy dog.";
$swears = array(
"BROWN" => "BRO.WN",
"fox" => "f.ox",
"Dog" => "D.og"
);
$string_arr = explode(" ",$string);
$swears_arr = array_keys($swears);
foreach ($swears as $swear_key => $swear_word) {
foreach ($string_arr as $key => $word) {
if (preg_replace('/[^a-z]+/i', '', strtolower($word)) == strtolower($swear_key)) {
$string_arr[$key] = substr_replace($word, '.', 1, 0);
}
}
}
// put the sentence back together:
$new_string = implode(" ",$string_arr);
print_r($new_string);
?>
I have make a try like this:
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-13);
and the output work :
localhost/product/-/123456 cause this just for above link with 13 character after /-/123456
How to remove all? i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-(.*));
not work and error sintax.
and i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-999);
the output is empty..
Assume there are no number after localhost/product/-/123456, then I will just trim it with below
$string = "localhost/product/-/123456-Ebook-Guitar";
echo rtrim($string, "a..zA..Z-"); // localhost/product/-/123456
Another non-regex version, but require 5.3.0+
$str = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo dirname($str) . "/" . strstr(basename($str), "-", true); //localhost/product/-/123456
Heres a more flexibility way but involve in regex
$string = "localhost/product/-/123456-Ebook-Guitar";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
$string = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
This should match capture everything up to the number and remove everything afterward
regex101: localhost/product/-/123456-Ebook-Guitar
regex101: localhost/product/-/123456-Ebook-Guitar-1-pdf/
Not a one-liner, but this will do the trick:
$string = "localhost/product/-/123456-Ebook-Guitar";
// explode by "/"
$array1 = explode('/', $string);
// take the last element
$last = array_pop($array1);
// explode by "-"
$array2 = explode('-', $last);
// and finally, concatenate only what we want
$result = implode('/', $array1) . '/' . $array2[0];
// $result ---> "localhost/product/-/123456"
I want to replace some numbers in a string with the content of the array in the position which this number points to.
For example, replace "Hello 1 you are great", with "Hello myarray[1] you are great"
I was doing the next: preg_replace('/(\d+)/','VALUE: ' . $array[$1],$string);
But it does not work. How could I do it?
You should use a callback.
<?php
$str = 'Hello, 1!';
$replacements = array(
1 => 'world'
);
$str = preg_replace_callback('/(\d+)/', function($matches) use($replacements) {
if (array_key_exists($matches[0], $replacements)) {
return $replacements[$matches[0]];
} else {
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
Since you are using a callback, in the event that you actually want to use a number, you might want to encode your strings as {1} or something instead of 1. You can use a modified match pattern:
<?php
// added braces to match
$str = 'Hello, {1}!';
$replacements = array(
1 => 'world'
);
// added braces to regex
$str = preg_replace_callback('/\{(\d+)\}/', function($matches) use($replacements) {
if (array_key_exists($matches[1], $replacements)) {
return $replacements[$matches[1]];
} else {
// leave string as-is, with braces
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
However, if you are always matching known strings, you may want to use #ChrisCooney's solution because it offers less opportunity to screw up the logic.
The other answer is perfectly fine. I managed it this way:
$val = "Chris is 0";
// Initialise with index.
$adj = array("Fun", "Awesome", "Stupid");
// Create array of replacements.
$pattern = '!\d+!';
// Create regular expression.
preg_match($pattern, $val, $matches);
// Get matches with the regular expression.
echo preg_replace($pattern, $adj[$matches[0]], $val);
// Replace number with first match found.
Just offering another solution to the problem :)
$string = "Hello 1 you are great";
$replacements = array(1 => 'I think');
preg_match('/\s(\d)\s/', $string, $matches);
foreach($matches as $key => $match) {
// skip full pattern match
if(!$key) {
continue;
}
$string = str_replace($match, $replacements[$match], $string);
}
<?php
$array = array( 2 => '**', 3 => '***');
$string = 'lets test for number 2 and see 3 the result';
echo preg_replace_callback('/(\d+)/', 'replaceNumber', $string);
function replaceNumber($matches){
global $array;
return $array[$matches[0]];
}
?>
output
lets test for number ** and see *** the result
I'm having trouble finding a correct regex to achieve what I want.
I have a sentence like that :
Hi, my name is Stan, you are welcome, hello.
and I would like to transform it like that :
[hi|hello|welcome], my name is [stan|jack] you are [hi|hello|welcome] [hi|hello|welcome].
Right now my regex is half working, because somes words are not replaced, and those replaced are deleting some characters
Here is my test code
<?php
$test = 'Hi, my name is Stan, you are welcome, hello.';
$words = array(
array('hi', 'hello', 'welcome'),
array('stan', 'jack'),
);
$result = $test;
foreach ($words as $group) {
if (count($group) > 0) {
$replacement = '[' . implode('|', $group) . ']';
foreach ($group as $word) {
$result = preg_replace('#([^\[])' . $word . '([^\]])#i', $replacement, $result);
}
}
}
echo $test . '<br />' . $result;
Any help will be appreciated
The regex you are using is overcomplicated. You simply need to use a regex substitution using regular brackets ():
<?php
$test = 'Hi, my name is Stan, you are welcome, hello.';
$words = array(
array('hi', 'hello', 'welcome'),
array('stan', 'jack'),
);
$result = $test;
foreach ($words as $group) {
if (count($group) > 0) {
$imploded = implode('|', $group);
$replacement = "[$imploded]";
$search = "($imploded)";
$result = preg_replace("/$search/i", $replacement, $result);
}
}
echo $test . '<br />' . $result;
Your regular expression:
'#([^\[])' . $word . '([^\]])#i'
matches one character before and after $word as well. And as they do, they replace it. So your replacement string needs to reference these parts, too:
'$1' . $replacement . '$2'
Demo
preg_replace supports array as parameter. No need to iterate with a loop.
$s = array("/(hi|hello|welcome)/i", "/(stan|jack)/i");
$r = array("[hi|hello|welcome]", "[stan|jack]");
preg_replace($s, $r, $str);
or dynamically
$test = 'Hi, my name is Stan, you are welcome, hello.';
$s = array("hi|hello|welcome", "stan|jack");
$r = array_map(create_function('$a','return "[$a]";'), $s);
$s = array_map(create_function('$a','return "/($a)/i";'), $s);
echo preg_replace($s, $r, $str);
//[hi|hello|welcome], my name is [stan|jack], you are [hi|hello|welcome], [hi|hello|welcome].