Way to Have String.Replace Only Hit "Whole Words"

Way to have String.Replace only hit whole words

A regex is the easiest approach:

string input = "test, and test but not testing.  But yes to test";
string pattern = @"\btest\b";
string replace = "text";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);

The important part of the pattern is the \b metacharacter, which matches on word boundaries. If you need it to be case-insensitive use RegexOptions.IgnoreCase:

Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);

str_replace on whole words

So if I understand you correctly $result['avis'] is the string you want to format word by word?

You could try to explode your text with ' ', which will separate it in words and then do direct comparisons word by word and then implode it back.

$avis = explode(' ', $result['avis']);
$cnt = count($avis); // Don't use count() in your for loops it is a huge perfomance hit
for($i=0; $i < $cnt; $i++){
if(in_array($avis[$i], $arr1)){
$avis[$i] = "<font color='red'><u>".$avis[$i]."</u></font>";
}
elseif(in_array($avis[$i], $arr3))...
// Do the other replacements here
}
$avis = implode(' ', $avis);

How to search and replace exact matching strings only

You can use Regex to do this:

Extension method example:

public static class StringExtensions
{
public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find;
return Regex.Replace(input, textToFind, replace);
}
}

Usage:

  string text = "Add Additional String to text box";
string result = text.SafeReplace("Add", "Insert", true);

result: "Insert Additional String to text box"

C# string replace if exact match is found

When replacing whole words, try using regular expressions (\b to mark word's border):

 using System.Text.RegularExpressions;

...

string strExpression = "hey! Hello World. SpecialDayForMe";
string toFind = "SpecialDay";

strExpression = Regex.Replace(
strExpression,
@"\b" + Regex.Escape(toFind) + @"\b", // Regex.Escape to be on the safe side
"ABC");

It matches "Hello world. SpecialDay for me" as well as "SpecialDay," and "SpecialDay.".

str_replace replace only match words

Update:

HD, thank you! your solution works for me!

This is work version

function replace_text_wps($text){

$dir = plugin_dir_path( __FILE__ );
$file= $dir."bad2.list";

$badlist = file($file, FILE_IGNORE_NEW_LINES);

$replacement = "[CENSORED]";
$badlist = array_map(function($v) { return "\b". $v ."\b"; }, $badlist);
foreach($badlist as $f) {
$text = preg_replace("/".$f."/u", $replacement, $text);


return $text;
}

Javascript/Jquery - how to replace a word but only when not part of another word?

You can use word boundaries (\b), which match 0 characters, but only at the beginning or end of a word. I'm also using grouping (the parentheses), so it's easier to read an write such expressions.

var regex = /\b(apple|pear|orange|banana)\b/ig; 

BTW, in your example you don't need to use a function. This is sufficient:

function rude(string) {
var regex = /\b(apple|pear|orange|banana)\b/ig;
return string.replace(regex, '');
}

c# replace string if it is not a substring

Solved the problem using a two-loop-through approach as follows...

List<string> keys = new List<string>();
keys.Add("Word1"); // ... and so on
// IMPORTANT: algorithm works only when we are sure that one key cannot be
// included in another key with higher index. Also, uniqueness is
// guaranteed by construction, although the routine would work
// duplicate key...!
keys = keys.OrderByDescending(x => x.Length).ThenBy(x => x).ToList<string>();
// first loop: replace with some UNIQUE key hash in text
foreach(string key in keys) {
txt.Replace(key, string.Format("!#someUniqueKeyNotInKeysAndNotInTXT_{0}_#!", keys.IndexOf(key)));
}
// second loop: replace UNIQUE key hash with corresponding values...
foreach(string key in keys) {
txt.Replace(string.Format("!#someUniqueKeyNotInKeysAndNotInTXT_{0}_#!", keys.IndexOf(key)), string.Format("{0}{1}{2}", preStr, key, postStr));
}


Related Topics



Leave a reply



Submit