replace elements in string PHP - php

I have a string "Hello World !" and I want to replace some letters in it and receive result like "He!!! W!r!d !" it's means that i changed all "l" and "o" to "!"
I found function preg_replace();
function replace($s){
return preg_replace('/i/', '!', "$s");
}
and it works with exactly one letter or symbol, and I want to change 2 symbols to "!".

Change your function as such;
function replace($s) {
return preg_replace('/[ol]/', '!', $s);
}
Read more on regular expressions here to get further understanding on how to use regular expressions.

Since you are already using regular expressions, why not really use then to work with the pattern you are really looking for?
preg_replace('/l+/', '!', "Hello"); // "He!o" ,so rewrites multiple occurances
If you want exactly two occurances:
preg_replace('/l{2}/', '!', "Helllo"); // "He!lo" ,so rewrites exactly two occurances
Or what about that:
preg_replace('/[lo]/', '!', "Hello"); // "He!!!" ,so rewrites a set of characters
Play around a little using an online tool for such: https://regex101.com/

This can be accomplished either using preg_replace() like you're trying to do or with str_replace()
Using preg_replace(), you need to make use of the | (OR) meta-character
function replace($s){
return preg_replace('/l|o/', '!', "$s");
}
To do it with str_replace() you pass all the letters that you want to replace in an array, and then the single replacing character as just a string (or, if you want to use multiple replacing characters, then also pass an array).
str_replace(array("l","o"), "!", $s);
Live Example

Using preg_replace like you did:
$s = 'Hello World';
echo preg_replace('/[lo]/', '!', $s);
I think another way to do it would be to use an array and str_replace:
$s = 'Hello World';
$to_replace = array('o', 'l');
echo str_replace($to_replace, '!', $s);

Related

how to remove everything before second occurance of underscore

I couldn't find the solution using search.
I am looking for a php solution to remove all character BEFORE the second occurance of and underscore (including the underscore)
For example:
this_is_a_test
Should output as:
a_test
I currently have this code but it will remove everything after the first occurance:
preg_replace('/^[^_]*.s*/', '$1', 'this_is_a_test');
Using a slightly different approach,
$s='this_is_a_test';
echo implode('_', array_slice( explode( '_', $s ),2 ) );
/* outputs */
a_test
preg_replace('/^.*_.*_(.*)$/U', '$1', 'this_is_a_test');
Note the U modifier which tells regex to take as less characters for .* as possible.
You can also use explode, implode along with array_splice like as
$str = "this_is_a_test";
echo implode('_',array_splice(explode('_',$str),2));//a_test
Demo
Why go the complicated way? This is a suggestion though using strrpos and substr:
<?php
$str = "this_is_a_test";
$str_pos = strrpos($str, "_");
echo substr($str, $str_pos-1);
?>
Try this one.
<?php
$string = 'this_is_a_test';
$explode = explode('_', $string, 3);
echo $explode[2];
?>
Demo
I'm still in favor of a regular expression in this case:
preg_replace('/^.*?_.*?_/', '', 'this_is_a_test');
Or (which looks more complex here but is easily adjustable to N..M underscores):
preg_replace('/^(?:.*?_){2}/', '', 'this_is_a_test');
The use of the question mark in .*? makes the match non-greedy; and the pattern has been expanded from the original post to "match up through" the second underscore.
Since the goal is to remove text the matched portion is simply replaced with an empty string - there is no need for a capture group or to use such as the replacement value.
If the input doesn't include two underscores then nothing is removed; such can be adjusted, very easily with the second regular expression, if the rules are further clarified.

Cut string from end to specific char in php

I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.
Thanks
In this special case, an url, use basename() :
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace(), like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.
Use
explode() AND end()
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Working Demo
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));

Trim string based on certain characters

I've got a string which goes something like myString__sfsdfsf
All I know is that there is a __ somewhere in the string. Content of the string and number of characters is unknown.
I want to remove the __ and all characters that follow so I am left with just myString. How can I achieve this using PHP?
This can be done in several ways. PHP has lots of string functions. You can pick one depending on your requirements. Here are some ways:
Use substr() and strpos():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__')); // => myString
Or use strtok():
echo strtok($str, '__'); // => myString
Or, maybe even explode():
echo explode('__', $str)[0]; // => myString
You can make use of strpos() and substr():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__'));
This should be quite fast. However if you need something more fancy than that, you probably want to look into regular expressions, e.g. preg_match().
Use list() and explode():
list($string,) = explode('_', 'myString__sfsdfsf');
echo $string; // Outputs: myString
A str_replace() would also work
$string = str_replace('__', '', $string);
Ignore that, didn't read your question properly

Replacing the last occurrence of a character in a string

I have a little issue I'm trying to find a solution for.
Basically, imagine you have the following string:
$string = 'Hello I am a string';
And you'd like it to end with something like the folowing:
$string = 'Hello I am a string';
Simply, replacing the last occurrence of a space, with a non-breaking space.
I'm doing this because I don't want the last word in a heading to be on its own. Simply because when it comes to headings:
Hello I am a
string
Doesn't look as good as
Hello I am
a string
How does one do such a thing?
Code from this example will do the trick:
// $subject is the original string
// $search is the thing you want to replace
// $replace is what you want to replace it with
substr_replace($subject, $replace, strrpos($subject, $search), strlen($search));
echo preg_replace('/\s(\S*)$/', ' $1', 'Hello I am a string');
Output
Hello I am a string
CodePad.
\s matches whitespace characters. To match a space explictly, put one in (and change \S to [^ ]).
This would do the trick:
$string = preg_replace('/([\s\S]+)\s(\w)$/','$1 $2',$string);
as per pounndifdef's answer, however i needed to decode the HTML entity like so:
substr_replace($subject, html_entity_decode($replace), strrpos($subject, $search), strlen($search));
also worked using alex's answer:
preg_replace('/\s(\S*)$/', html_entity_decode(' ').'$1', 'Hello I am a string');
Use str_replace() like normal, but reverse the string first. Then, reverse it back.

Replace after a needle in a string?

I have a string, something like
bbbbabbbbbccccc
Are there any way for me to replace all the letters "b" after the only one letter "a" into "c" without having to split the string, using PHP?
bbbbacccccccccc
odd question.
echo preg_replace('/a(.*)$/e', "'a'.strtr($1, 'b', 'c')", 'bbbabbbbbccccc');
preg_replace matches everything to the right of 'a' with regex. the e modifier in the regex evaluates the replacement string as code. the code in the replacement string uses strtr() to replace 'b's with 'c's.
Here are three options.
First, a split. Yes, I know you want to do it without a split.
$string = 'bbbbabbbbbccccc';
$parts = preg_split('/(a)/', $string, 2, PREG_SPLIT_DELIM_CAPTURE);
// Parts now looks like:
// array('bbb', 'a', 'bbbbcccc');
$parts[2] = str_replace('b', 'c', $parts[2]);
$correct_string = join('', $parts);
Second, a position search and a substring replacement.
$string = 'bbbbabbbbbccccc';
$first_a_index = strpos($string, 'a');
if($first_a_index !== false) {
// Now, grab everything from that first 'a' to the end of the string.
$replaceable = substr($string, $first_a_index);
// Replace it.
$replaced = str_replace('b', 'c', $replaceable );
// Now splice it back in
$string = substr_replace($string, $replaced, $first_a_index);
}
Third, I was going to post a regex, but the one dqhendricks posted is just as good.
These code examples are verbose for clarity, and can be reduced to one-or-two-liners.
$s = 'bbbbabbbbbccccc';
echo preg_replace('/((?:(?!\A)\G|(?<!a)a(?!a))[^b]*)b/', '$1c', $s);
\G matches the position where the previous match ended. On the first match attempt, \G matches the beginning of the string like \A. We don't want that, so we use (?!\A) to prevent it.
(?<!a)a(?!a) matches an a that's neither preceded nor followed by an a. The a is captured in group #1 so we can plug it back into the replacement with $1.
This is a "pure regex" solution, meaning it does the whole job in one call to preg_replace and doesn't rely on embedded code and the /e modifier. It's good to know in case you ever find yourself working within those constraints, but it definitely shouldn't be your first resort.

Categories