Example String:
AAAAAA BBBBB CCCCCCC
Output:
AAAXXX BBXXX CCCCXXX
I need to hide every last 3 chars of words. I tried str_replace but I can't make it. Thanks for help
$replacement = "***";
if (stripos($name, ' ') !== false) {
$star = substr($name, 0, -3).$replacement;
}
I tried this but code only hide last word's 3 char. I need every word. Thanks
You need to split your string up, replace the last three characters, and then reassemble it.
$replacement = "***";
// break your string into an array based on the spaces
$temp = explode(' ', $name) ;
// our temporary name
$newName = '' ;
// loop through each part of the original name
foreach($temp as $section) {
// append our modified string along with a space
$newName .= substr($section, 0, -3).$replacement . ' ' ;
}
// set $name = $newName without the trailing space
$name = substr($newName,0,-1) ;
$replacement = "***";
$star = "";
$pieces = explode(" ", $name);
foreach ($pieces as $piece){
$star .= substr($piece, 0, -3).$replacement." ";
}
Try this function,
function replaceLastThreeChars($string){
$reversed_string = strrev($string);
$replaced_string = str_replace(substr($reversed_string,0,3),"XXX",$reversed_string);
return strrev($replaced_string);
}
If you have a sentence, then you can slice it using spaces and call to this function and finally recreate the sentence.
Related
I have this code:
$words = ['mleko', 'masło'];
$words = explode(' ', $value); // create an array of words
foreach($words as $word) { //iterate through words
$word = preg_replace('/[^\w]/uis', '', $word);
if (in_array(mb_strtolower($word), $allergens)) {
$return .= "<b>" . $word . "</b> ";
} else {
$return .= $word . " ";
}
}
The above code works fine, but it deletes characters like:,. e.t.c.
How can I fix it? :)
Problem jest w podejściu jakie zastosowałeś. Nie tylko w linii
$word = preg_replace('/[^\w]/uis', '', $word);
which should be extended with the characters of the Polish alphabet (the range of the \w class is [a-zA-Z0-9_], remember to mention the range of lowercase and uppercase characters separately) like in this line
$word = preg_replace('/[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/uis', '', $word);
Moreover, I believe that the above line is used incorrectly. In my opinion, you should save the result of this operation in another variable as below
$rawWord = preg_replace('/[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/uis', '', $word);
Thanks to this, you have access to both the purified and the original value, which you can use in this way
if (in_array(mb_strtolower($rawWord), $allergens)) {
$return .= str_replace($rawWord, "<b>{$rawWord}</b> ", $word);
} else {
$return .= $word;
}
With this approach, however, you will still miss some characters. Even spaces that you filtered out with explode earlier. In my opinion, instead of concatenating a string, you should build an array and finally concatenate it with spaces. Complete code below.
$allergens = ['jogurt', 'jaja', 'żytni', "jogurt", "banan"];
$value = 'Chleb żytni, masło z mleka, jogurt naturalny z mleka, jaja, pieczeń rzymska z kaszą gryczaną.';
$returns = [];
$words = explode(' ', $value); // create an array of words
foreach($words as $word) { //iterate through words
$rawWord = preg_replace('/[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/uis', '', $word);
if (in_array(mb_strtolower($rawWord), $allergens)) {
$returns[] = str_replace($rawWord, "<b>{$rawWord}</b>", $word);
} else {
$returns[] = $word;
}
}
$return = implode(' ', $returns);
Look at this line
$returns[] = str_replace($rawWord, "<b>{$rawWord}</b>", $word);
Replaces the original word (containing the characters you want to ignore) with cleaned and bold version of the word. This keeps all characters (like commas) stuck to the word.
In the $return variable at the end you will get something like this
Chleb żytni, masło z mleka, jogurt naturalny z mleka, jaja, pieczeń rzymska z kaszą gryczaną.
I've been working with this code
<?php
class PerchTemplateFilter_sol_en_cat_path extends PerchTemplateFilter {
public function filterAfterProcessing($value, $valueIsMarkup = false) {
// ORIGINAL STRING: solutions-en/rail-technologies/track-components/name-of-product
$mystring = $value;
$replace = ['solutions-en', '%2F'];
$str = '';
$oldstr = str_replace($replace, $str, $mystring);
$str_to_insert = 'XXX';
$findme = '/';
$pos = strpos($mystring, $findme); // I NEED THIS TO INSERT $str_to_insert AFTER THE SECOND FORWARD SLASH FOUND IN THE ORIGINAL STRING?
$value = substr_replace($oldstr, $str_to_insert, $pos, 0);
return $value;
// $value: /rail-technologies/track-components/XXX/name-of-product
// Insert string at specified position
// https://stackoverflow.com/questions/8251426/insert-string-at-specified-position
}
}
PerchSystem::register_template_filter('sol_en_cat_path', 'PerchTemplateFilter_sol_en_cat_path');
?>
My string is: solutions-en/rail-technologies/track-components/name-of-product
I want to end up with: /rail-technologies/XXX/track-components/name-of-product
XXX is only a placeholder value
I guess I need to do something with $pos to set where I want XXX to be added to the string.
I need to insert after the second forward slash, as the string may contain different text
The code above outputs this string: /rail-technoXXXlogies/track-components/ewosr-switch-lock
I can't seem to figure out how to insert XXX after the second forward slash.
Hope someone can provide some help.
How about explode to array, then implode the first two items.
Join with xxx and implode the rest?
function AddInTheMiddle($start, $where, $what){
$arr = explode("/", $what);
$str = implode("/", array_splice($arr,$start,$where)) . '/xxx/' . implode("/", $arr);;
return $str;
}
$str = 'solutions-en/rail-technologies/track-components/name-of-product';
$str = AddInTheMiddle(1, 2, $str);
https://3v4l.org/m98io
Thank you Andreas, your post gave me the nudge I needed. I did this in the end.
// ORIGINAL $value: solutions-en/rail-technologies/track-components/name-of-product
$str = explode("/", $value);
$value = $str[1] . '/' . 'solutions' . '/' . $str[2] . '/';
return $value;
// Removed: solutions-en
// Added: solutions
// $value: rail-technologies/solutions/track-components/name-of-product
I was able to add the name-of-product to the end of the new string elsewhere in my template.
This is my string:
monkey/rabbit/cat/donkey/duck
If my variable is cat...
$animal = cat
... I want to remove everything coming after cat.
My desired result is:
monkey/rabbit/cat
I tried to use str_replace:
$subject = 'monkey/rabbit/cat/donkey/duck';
$trimmed = str_replace($animal, '', $subject);
echo $trimmed;
But here I get the result:
monkey/rabbit//donkey/duck
So it is just cutting out cat.
You can combine strpos with substr:
$pos = strpos($subject, $animal);
if ($pos !== false) {
$result = substr($subject, 0, $pos + strlen($animal));
}
If you wold like to make sure it only the full segments are erased, in case of a partial match, you could use the offset argument of strpos:
$pos = strpos($subject, $animal);
if ($pos !== false) {
$result = substr($subject, 0, strpos($subject, '/', $pos));
}
You can use explode in your case:
$string = "monkey/rabbit/cat/donkey/duck";
$val = explode("donkey", $string );
echo $val[0];
Result: monkey/rabbit/cat
PS* Ofcourse there are better ways to do this
My approach would be to explode by your variable.
Take the first part and append the variable.
<?php
$string = 'monkey/rabbit/cat/donkey/duck';
$animal = 'cat';
$temp = explode($animal,$string);
print $temp[0] . $animal;
Will output nicely
monkey/rabbit/cat
There's no need to use any of strpos, strlen, substr or donkeys
<?php
$animal="cat";
$string1="monkey/rabbit/cat/donkey/duck";
$parts = explode($animal, $string1);
$res = $parts[0];
print("$res$animal")
?>
Here is a bit of explanation for what each step does:
$subject = 'monkey/rabbit/cat/donkey/duck';
$target = 'cat';
$target_length = strlen($target); // get the length of your target string
$target_index = strpos($subject, $target); // find the position of your target string
$new_length = $target_index + $target_length; // find the length of the new string
$new_subject = substr($subject, 0, $new_length); // trim to the new length using substr
echo $new_subject;
This can all be combined into one statement.
$new_subject = substr($subject, 0, strpos($subject, $target) + strlen($target));
This assumes your target is found. If the target is not found, the subject will be trimmed to the length of the target, which obviously is not what you want. For example, if your target string was "fish" the new subject would be "monk". This is why the other answer checks if ($pos !== false) {.
One of the comments on your question raises a valid point. If you search for a string that happens to be contained in one of the other strings, you may get unexpected results. There is really not a good way to avoid this problem when using the substr/strpos method. If you want to be sure to only match a complete word between your separators (/), you can explode by / and search for your target in the resulting array.
$subject = explode('/', $subject); // convert to array
$index = array_search($target, $subject); // find the target
if ($index !== false) { // if it is found,
$subject = array_slice($subject, 0, $index + 1); // remove the end of the array after it
}
$new_subject = implode('/', $subject); // convert back to string
I'm probably going to kop some flak for going down the RegExp route but...
$subject = 'monkey/rabbit/polecat/cat/catfish/duck';
$animal = "cat";
echo preg_replace('~(.*(?:/|^)' . preg_quote($animal) . ')(?:/|$).*~i', "$1", $subject);
This will ensure that your animal is wrapped immediately on either side with / characters, or that it's at the start or end of the string (i.e. monkey or duck).
So in this example it'll output:
monkey/rabbit/polecat/cat
Ending specifically with cat rather than stumbling at polecat or catfish
I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");
I have a string in PHP that is a URI with all arguments:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0
I want to completely remove an argument and return the remain string. For example I want to remove arg3 and end up with:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1
I will always want to remove the same argument (arg3), and it may or not be the last argument.
Thoughts?
EDIT: there might be a bunch of wierd characters in arg3 so my prefered way to do this (in essence) would be:
$newstring = remove $_GET["arg3"] from $string;
There's no real reason to use regexes here, you can use string and array functions instead.
You can explode the part after the ? (which you can get using substr to get a substring and strrpos to get the position of the last ?) into an array, and use unset to remove arg3, and then join to put the string back together.:
$string = "http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0";
$pos = strrpos($string, "?"); // get the position of the last ? in the string
$query_string_parts = array();
foreach (explode("&", substr($string, $pos + 1)) as $q)
{
list($key, $val) = explode("=", $q);
if ($key != "arg3")
{
// keep track of the parts that don't have arg3 as the key
$query_string_parts[] = "$key=$val";
}
}
// rebuild the string
$result = substr($string, 0, $pos + 1) . join($query_string_parts);
See it in action at http://www.ideone.com/PrO0a
preg_replace("arg3=[^&]*(&|$)", "", $string)
I'm assuming the url itself won't contain arg3= here, which in a sane world should be a safe assumption.
$new = preg_replace('/&arg3=[^&]*/', '', $string);
This should also work, taking into account, for example, page anchors (#) and at least some of those "weird characters" you mention but don't seem worried about:
function remove_query_part($url, $term)
{
$query_str = parse_url($url, PHP_URL_QUERY);
if ($frag = parse_url($url, PHP_URL_FRAGMENT)) {
$frag = '#' . $frag;
}
parse_str($query_str, $query_arr);
unset($query_arr[$term]);
$new = '?' . http_build_query($query_arr) . $frag;
return str_replace(strstr($url, '?'), $new, $url);
}
Demo:
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0#frag';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0&arg4=4';
$string[] = 'http://domain.com/php/doc.php';
$string[] = 'http://domain.com/php/doc.php#frag';
$string[] = 'http://example.com?arg1=question?mark&arg2=equal=sign&arg3=hello';
foreach ($string as $str) {
echo remove_query_part($str, 'arg3') . "\n";
}
Output:
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1#frag
http://domain.com/php/doc.php?arg1=0&arg2=1&arg4=4
http://domain.com/php/doc.php
http://domain.com/php/doc.php#frag
http://example.com?arg1=question%3Fmark&arg2=equal%3Dsign
Tested only as shown.