Stop replacing text in string after first replacement in PHP - php

Here is an example:
$original_string = 'I like apples very much. I want an apple.';
$temp_string = str_replace('apples', '_apples_', $original_string);
// $temp_string is now: I like _apples_ very much. I want an apple.
$final_string = str_replace('apple', '_apple_', $temp_string);
// $final_string is now: I like __apple_s_ very much. I want an _apple_.
This is not what I intend to do. I want the final string to be:
I like _apples_ very much. I want an _apple_.
This is what I tried to do:
$original_string = 'I like apples very much. I want an apple.';
$final_string = str_replace(['apples', 'apple'], ['_apples_', '_apple_'], $original_string);
echo $original_string;
// I like __apple_s_ very much. I want an _apple_.
Reversing the replacement order does not help either:
$original_string = 'I like apples very much. I want an apple.';
$original_string = str_replace(['apple', 'apples'], ['_apple_', '_apples_'], $original_string);
echo $original_string;
// I like _apple_s very much. I want an _apple_.
What should I do?
Thanks.

You can use preg_replace it use Regular Expression instead of string for the replacement
$original_string = 'I like apples very much. I want an apple.';
$final_string = preg_replace("/(apples?)/", "_$1_", $original_string);
echo $final_string;
Regex explanation : https://regex101.com/r/EzxqWR/2 and demo : https://3v4l.org/uTDIs
(1) (2)
vvvvvvvv vvvv
preg_replace("/(apples?)/", "_$1_", $original_string);
It will search string apple or apples
and will put the result to $1 and became _apple_ or _apples_
Hope the explanation is clear, and sorry for bad explanation

Related

Search in a php string for a count of numbers

I have variables like this:
Example 1: 709000-037602-14-5_ABC
Example 2: 702000-025801-12_4_DEF
Example 3: 210104-1041-011866_GHI
How can i cut the data?
My idea is to seach for the underscore BUT the example 1 does cut on the false segment.
I want to get this variables: $var=709000-037602-14-4, $var=709000-037602-14_4 and $var1=210104-1041-011866
(ABC, DEF, GHI are not important. I only wanted to show i cant search for it.)
For now my used function is:
$var= strstr($var_original, '_', true);
Question: Can I count the number of numbers on the secound sequment (037602, 025801 or 1041) because this is 6 OR 4 digits.
Thanks for help :)
You can use:
explode
array_pop
implode
Like:
$string = '709000-037602-14-5_ABC';
$string1 = '702000-025801-12_4_DEF';
echo explodeCode($string).'<br>'. explodeCode($string1);
function explodeCode($code){
$final = explode('_', $code);
array_pop($final);
return (count($final) === 2) ? implode('_', $final) : implode('', $final);
}
Output:
709000-037602-14-5
702000-025801-12_4
After your multiple example i suppose is better use preg_split like:
$string = '709000-037602-14-5_ABC';
$string1 = '702000-025801-12_4_DEF';
$string2 = '709000-037602-14-5_ABC_test_no1';
echo explodeCode($string).'<br>'. explodeCode($string1). '<br>'. explodeCode($string2);
function explodeCode($code){
return preg_split("/\_[A-Z]/", $code)[0];
}
Output:
709000-037602-14-5
702000-025801-12_4
709000-037602-14-5

Reduce whole text to some words in PHP

I have a problem. I need a "text reducer".
What i mean: I wrote to text area any words, for example: John Doe is good boy; Then i press some button, and it will get something like:
John Doe
So, it will only output defined worlds, like John Doe, or milk or something like that
Thanks for your help
If you know a black list of words you want to strip out, you could use the array replace function: str_replace:
http://php.net/manual/en/function.str-replace.php
like this:
$blacklist = ['ugly', 'bad', 'censored'];
$yourString = str_replace($yourString, $blacklist, '');
This will remove every word in your blacklist, from your input string.
If you need a whitelist based filter, you could use split your string into an array of words, and then use the array_filter function:
http://php.net/manual/en/function.preg-split.php
http://php.net/manual/en/function.array-filter.php
using something similar to:
$whitelist = ['good', 'neat', 'stuff'];
$tokens = preg_split("/[\s,]+/", $yourString);
$filtered = array_filter($tokens, function ($item) {
return in_array($token, $whitelist);
});
$finalString = implode(' ', $filtered);
Yes you can write a function in this case it receives an array as parameter, but if is static, you could save it on the function.
Also, this could work using a regex with preg_match, but i'll leave that for you.
Currently ignores case thanks to `strtolower', if you don't want to ignore the case, remove this function calls.
function printWhiteListedText($arrWhitelist, $str){
$auxStr = "";
foreach($arrWhitelist as $word){
if(strpos(strtolower($str), strtolower($word)) > -1){
$auxStr .= $word . ' ';
}
}
return trim($auxStr);
}
echo printWhiteListedText(['Hello', 'world'], 'hello this world is great');

Cutting a string at a special character in PHP

I'm searching a function to cut the following string and get all content BEFORE and AFTER
I need this part<!-- more -->and also this part
Result should be
$result[0] = "I need this part"
$result[1] = "and also this part"
Appreciate any help!
Use the explode() function in PHP like this:
$string = "I need this part<!-- more -->and the other part.
$result = explode('<!-- more -->`, $string) // 1st = needle -> 2nd = string
Then you call your result:
echo $result[0]; // Echoes: I need that part
echo $result[1]; // Echoes: and the other part.
You can do this pretty easily with regular expressions. Somebody out there is probably crying for parsing HTML/XML with regular expressions, but without much context, I'm going to give you the best that I've got:
$data = 'I need this part<!-- more -->and also this part';
$result = array();
preg_match('/^(.+?)<!--.+?-->(.+)$/', $data, $result);
echo $result[1]; // I need this part
echo $result[2]; // and also this part
If you are parsing HTML, considering reading about parsing HTML in PHP.
Use preg_split. Maybe something like this:
<?php
$result = preg_split("/<!--.+?-->/", "I need this part<!-- more -->and also this part");
print_r($result);
?>
Outputs:
Array
(
[0] => I need this part
[1] => and also this part
)

PHP, regex and multi-level curly brackets

I've got a string which consists of few sentences which are in curly brackets that I want to remove. That would be not that hard to do (as I know now.), but the real trouble is it's multilevel and all I want to strip is the top level brackets and leave everything inside intact. It looks something like this:
{Super duper {extra} text.} {Which I'm really {starting to} hate!} {But I {won't give up} so {easy}!} {Especially when someone is {gonna help me}.}
I want to create an array that would consist of those four entries:
Super duper {extra} text.
Which I'm really {starting to} hate!
But I {won't give up} so {easy}!
Especially when someone is {gonna help me}.
I have tried two ways, one was preg_split which didn't do much good:
$key = preg_split('/([!?.]{1,3}\} \{)/',$key, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();
for ($i=0, $n=count($key)-1; $i<$n; $i+=2) {
$sentences[] = $key[$i].$key[$i+1]."<br><br>";
}
Another one was using preg_match_all which was quite good until I realized I had those brackets multilevel:
$matches = array();
$key = preg_match_all('/\{[^}]+\}/', $key, $matches);
$key = $matches[0];
Thanks in advance! :)
You can use a recursive expression like this:
/{((?:[^{}]++|(?R))*+)}/
The desired results will be in the first capturing group.
Usage, something like:
preg_match_all('/{((?:[^{}]++|(?R))*+)}/', $str, $matches);
$result = $matches[1];
$x="foo {bar {baz}} whee";
$re="/(^[^{]*){(.*)}([^}]*)$/";
print preg_replace($re, "\\1\\2\\3", $x) . "\n";'
returns:
foo bar {baz} whee

multiple string replace

I need to replace multiple text with it's associated text
Example: I have string like: "apple is a great fruit"
Now I need to replace "apple" to "stackoverflow", and "fruit" to "website"
I know I can use str_replace, but is there any other way? str_replace would be slow in my case, because I need to replace atleast 5 to 6 words
Help appreciated.
<?php
$a = array('cheese','milk');
$b = array('old cow','udder');
$str = 'I like cheese and milk';
echo str_replace($a,$b,$str); // echos "I like old cow and udder"
Alternatively, if you don't like to look of that (worried of miss matching array values) then you could do:
$start = $replace = $array();
$str = "I like old cow and udder"
$start[] = 'cheese';
$replace[] = 'old cow';
$start[] = 'milk';
$replace[] = 'udder';
echo str_replace($start,$replace,$str); // echos "I like old cow and udder"
edit: I see dnl has edited the question and put emphasis on the fact that str_replace would be too slow. In my interpretation of the question it is because the user was not aware that they would use arrays in str_replace.
if u know all the word sequence and also replaced word then use below technique
$trans = array( "apple" => "stackoverflow", "fruit" => "website");
echo strtr("apple is a great fruit", $trans); // stackoverflow is a great website
Reference
For your purpose str_replace seams to be already the fastest solution.
str_replace is faster than strstr
Source: http://www.simplemachines.org/community/index.php?topic=175031.0

Categories