问题
i am facing an issue here , trying to replace string with another under a condition. check the example :
$data = '
tony is playing with toys.
tony is playing with "those toys that are not his" ';
so i want to replace toys with cards . but only which is NOT in ques (").
i know how to replace all words that are toys .
$data = str_replace("toys", "cards",$data);
but i don't know how to add a condition which specifies to replace only the one's which are not in the (").
can anyone help please ?
回答1:
Here's one simple way to do it. Split/explode your string using quotation marks. The first (0
-index) element and each even-numbered index in the resulting array is unquoted text; the odd numbers are inside quotes. Example:
Test "testing 123" Test etc.
^0 ^1 ^2
Then, just replace the magic words (toys) with the replacement (cards) in only the even-numbered array elements.
Sample code:
function replace_not_quoted($needle, $replace, $haystack) {
$arydata = explode('"', $haystack);
$count = count($arydata);
for($s = 0; $s < $count; $s+=2) {
$arydata[$s] = preg_replace('~'.preg_quote($needle, '~').'~', $replace, $arydata[$s]);
}
return implode($arydata, '"');
}
$data = 'tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys';
echo replace_not_quoted('toys', 'cards', $data);
So, here, the sample data is:
tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys
The algorithm works as expected and produces:
tony is playing with cards.
tony is playing with cards... "those toys that are not his" but they are "nice toys," those cards
回答2:
You'll need to parse the string to identify the regions that are not within quotes. You can do this with a state-machine or regular-expression that supports counting.
Here's a pseudocode example:
typedef Pair<int,int> Region;
List<Region> regions;
bool inQuotes = false;
int start = 0;
for(int i=0;i<str.length;i++) {
char c = str[i];
if( !inQuotes && c == '"' ) {
start = i;
inQuotes = true;
} else if( inQuotes && c == '"' ) {
regions.add( new Region( start, i ) );
inQuotes = false;
}
}
Then split the string up according to regions
, each alternate region will be in quotes.
Challenge for the reader: get it so it handles escaped quotes :)
回答3:
You could use regex and use a negative lookaround to find the line without the quotes then do a string replace on that.
^((?!\"(.+)?toys(.+)?\").)*
e.g.
preg_match('/^((?!\"(.+)?toys(.+)?\").)*/', $data, $matches);
$line_to_replace = $matches[0];
$string_with_cards = str_replace("toys", "cards", $line_to_replace);
OR if there are multiple matches you might want to iterate over the array.
http://rubular.com/r/t7epW0Tbqi
来源:https://stackoverflow.com/questions/19848516/replace-string-on-condition-php