preg_replace: How to not remove the whole part? - php

I got this string:
$string = "hello123hello237ihello523";
I want to search for an "o" followed by a number. Then I want to remove only the "o".
I've been trying:
preg_replace("/kl[0-9]/", "", $string);
The problem is that is removes the number as well. I only want to remove the "o". Any ideas?

use positive lookahead:
echo preg_replace("/o(?=[0-9])/", "", $string);
For more information: http://www.regular-expressions.info/lookaround.html
One other option is:
echo preg_replace("/o([0-9])/", "\\1", $string);
This will replace the o[number] with [number]

You could use back references:
echo preg_replace('/o([0-9])/', '$1', $string);
See the documentation for information on referencing subpatterns.

Related

How to delete string with regex preg_replace php

i have full string like this:
Route::post('asdasdasdad/{param1}/{param2}', 'Admin\RouteController#a212e12e');.
and want to delete that route so in preg_replace i focus on
Route::post('asdasdasdad as start text and
Admin\RouteController#a212e12e'); as last text.
here what i try
preg_replace("/Route::post('asdasdasdad\(.*Admin\RouteController#a212e12e');\s*/s", "", $string);
but its not working.
you have some errors in your regex, some un-escaped regex characters. try this
preg_replace("/Route::post\('asdasdasdad.*Admin\\\\RouteController#a212e12e'\);\s*/s", "", $string);
if you want to replace multiple lines in one go
preg_replace_all("/Route::post\('asdasdasdad.*Admin\\\\RouteController#a212e12e'\);\s*/s", "", $string);
witch works as if you add the multi line modifier to your regex
$string = file_get_contents('route.php');
$string = preg_replace("/Route::post\('asdasdasdad.*Admin\\\\RouteController#a212e12e'\);\s*/s", "", $string);
echo $string;
you get the line with EOL removed

PHP exploding url from text, possible?

i need to explode youtube url from this line:
[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]
It is possible? I need to delete [embed] & [/embed].
preg_match is what you need.
<?php
$str = "[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]";
preg_match("/\[embed\](.*)\[\/embed\]/", $str, $matches);
echo $matches[1]; //https://www.youtube.com/watch?v=L3HQMbQAWRc
$string = '[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]';
$string = str_replace(['[embed]', '[/embed]'], '', $string);
See str_replace
why not use str_replace? :) Quick & Easy
http://php.net/manual/de/function.str-replace.php
Just for good measure, you can also use positive lookbehind's and lookahead's in your regular expressions:
(?<=\[embed\])(.*)(?=\[\/embed\])
You'd use it like this:
$string = "[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]";
$pattern = '/(?<=\[embed\])(.*)(?=\[\/embed\])/';
preg_match($pattern, $string, $matches);
echo $match[1];
Here is an explanation of the regex:
(?<=\[embed\]) is a Positive Lookbehind - matches something that follows something else.
(.*) is a Capturing Group - . matches any character (except a newline) with the Quantifier: * which provides matches between zero and unlimited times, as many times as possible. This is what is matched between the groups prior to and after. This are the droids you're looking for.
(?=\[\/embed\]) is a Positive Lookahead - matches things that come before it.

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.

PHP : Separate alphanumeric word with space in string

How can separate alphanumeric value with space in one statement
Example :
$arr="new stackoverflow 244code 7490script design";
So how can possible to separate alpha and number with space like :
$arr="new stackoverflow 244 code 7490 script design";
You can use preg_split() function
Check demo Codeviper
preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");
PHP
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design"));
Result
Array ( [0] => new stackoverflow 244 [1] => code 7490 [2] => script design )
You can also use preg_replace() function
Check demo Codeviper
PHP
echo preg_replace('#(?<=\d)(?=[a-z])#i', ' ', "new stackoverflow 244code 7490script design");
Result
new stackoverflow 244 code 7490 script design
Hope this help you!
You may use preg_replace (Example):
$arr = "new stackoverflow 244code 7490script design";
$newstr = preg_replace('#(?<=\d)(?=[a-z])#i', ' ', $arr);
echo $newstr; // new stackoverflow 244 code 7490 script design
The regex pattern used from user1153551's answer.
Use preg_replace like this:
$new = preg_replace('/(\d)([a-z])/i', "$1 $2", $arr);
regex101 demo
(\d) match and catches a digit. ([a-z]) matches and catches a letter. In the replace it puts back the digit, adds a space and puts back the letter.
If you don't want to use backreferences, you can use lookarounds:
$new = preg_replace('/(?<=\d)(?=[a-z])/i', ' ', $arr);
If you want to replace between letter and number as well...
$new = preg_replace('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', ' ', $arr);
regex101 demo
(?<=\d) is a positive lookbehind that makes sure that there is a digit before the current position.
(?=[a-z]) is a positive lookahead that makes sure that there is a letter right after the current position.
Similarly, (?<=[a-z]) makes sure there's a letter before the current position and (?=\d) makes sure there's a digit right after the current position.
An different alternative would be to split and join back with spaces:
$new_arr = preg_split('/(?<=\d)(?=[a-z])/i', $arr);
$new = implode(' ', $new_arr);
Or...
$new = implode(' ', preg_split('/(?<=\d)(?=[a-z])/i', $arr));
preg_split
preg_split — Split string by a regular expression
<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$matches = preg_split('#(?<=\d)(?=[a-z])#i', "new stackoverflow 244code 7490script design");
echo $matches['0'],' '.$matches['1'].' '.$matches['2'];
?>
WORKING DEMO

Split string at the first non-alphabetic character

How can I get a portion of the string from the beginning until the first non-alphabetic character?
Example strings:
Hello World
Hello&World
Hello5World
I'd like to get the "Hello" part
You need to use the preg_split feature.
$str = 'Hello&World';
$words = preg_split('/[^\w]/',$str);
echo $words[0];
You can access Hello by $words[0], and World by $words[1]
You can use preg_match() for this:
if (preg_match('/^([\w]+)/i', $string, $match)) {
echo "The matched word is {$match[1]}.";
}
Change [\w]+ to [a-z]+ if you do not want to match the 5 or any numeric characters.
Use preg_split. Split string by a regular expression
If you only want the first part, use preg_match:
preg_match('/^[a-z]+/i', $str, $matches);
echo $matches[0];
Here's a demo.
Use preg_split to get first part of alpha.
$array = preg_split('/[^[:alpha:]]+/', 'Hello5World');
echo $array[0];

Categories