RegEx preg_match_all() and white spaces in PHP - php

I have a Problem with RegEx and WhiteSpaces.
I want to split a Text in an Array which is marked with (....)
preg_match_all("/\([a-z0-9\s]+\)/i", $str,$a);
To catch whithe spaces I tried to use [\040] [\s] but nothing worked for me!
Is there a posibiltity to say [ANY Character DIGIT and WHITESPACES and special character] ?
greetz
fluxa

You can also said "any characters but not a )"
With your example :
preg_match_all("/\([^\)]+\)/i", $str, $a);

You could use a lazy search using.*? instead (which will stop matching as soon as it can, compared to greedy, .* which will match as much as possible).
Regex: \((.*?)\)
In code:
preg_match_all("#\((.*?)\)#", $str, $a);

Related

Regex to get only characters without space inside special tags

I have 2 texts in a string:
%Juan%
%Juan Gonzalez%
And I want to only be able to get %Juan% and not the one with the Space, I have been trying several Regexes witout luck. I currently use:
/%(.*)%/U
but it gets both things, I tried adding and playing with [^\s] but it doesnt works.
Any help please?
The issue is that . matches any character but a newline. The /U ungreedy mode only makes .* lazy and it captures a text from the % up to the first % to the right of the first %.
If your strings contain one pair of %...%, you may use
/%(\S+)%/
See the regex demo
The \S+ pattern matches 1+ characters other than a whitespace, and the whole [^\h%] negated character class that matches any character but a horizontal space and % symbol.
If you have multiple %...% pairs, you may use
/%([^\h%]+)%/
See another regex demo, where \h matches any horizontal whitespace.
PHP demo:
$re = '/%([^\h%]+)%/';
$str = "%Juan%\n%Juan Gonzalez%";
preg_match_all($re, $str, $matches);
print_r($matches[1]);

Regex: Select multiple lines between characters

I can't select multiple lines between two characters on regex.
how can i solve this?
{
example
example 1
}
I want to select 'example'. but i cant.
I tried this regex
#\n.*#
thank you
Your pattern does not do what you expect; it matches a newline character followed by any character except newline "zero or more" times. You need to use the s (dotall) modifier which forces the dot to match across newline sequences.
For example — matching everything between the two curly braces.
preg_match('/{(.*)}/s', $str, $match);
echo $match[1];

php separating words by using regex

I have a string and it contains some words that I want to reach, seperators can be any string that consist of , ; or a space.
Here is a example:
;,osman,ali;, mehmet ;ahmet,ayse; ,
I need to take words osman ali mehmet ahmet and ayse to an array or any type that I can use them one by one. I tried it by using preg function but i couldn't figure out.
If anyone help, I will be appreciative.
$words = preg_split('/[,;\s]+/', $str, -1, PREG_SPLIT_NO_EMPTY);
[,;\s] is a character group which means match any of the characters contained in this group.
\s matches any white space character (space, tab, newline, etc.). If this is too much just replace it with a space: [,; ].
+ means match one or more of the preceding symbol or group.
DEMO
http://www.regular-expressions.info/ is a good site to learn regular expressions.
You want to use preg_split and use [;, ]+ for your regex to split on
$keywords = preg_split("/[;, ]+/", $yourstring);
Split on non-word characters:
$array=preg_split("/\W+/", $string);

Remove number then a space from the start of a string

How would I go about removing numbers and a space from the start of a string?
For example, from '13 Adam Court, Cannock' remove '13 '
Because everyone else is going the \d+\s route I'll give you the brain-dead answer
$str = preg_replace("#([0-9]+ )#","",$str);
Word to the wise, don't use / as your delimiter in regex, you will experience the dreaded leaning-toothpick-problem when trying to do file paths or something like http://
:)
Use the same regex I gave in my JavaScript answer, but apply it using preg_replace():
preg_replace('/^\d+\s+/', '', $str);
Try this one :
^\d+ (.*)$
Like this :
preg_replace ("^\d+ (.*)$", "$1" , $string);
Resources :
preg_replace
regular-expressions.info
On the same topic :
Regular expression to remove number, then a space?
regular expression for matching number and spaces.
I'd use
/^\d+\s+/
It looks for a number of any size in the beginning of a string ^\d+
Then looks for a patch of whitespace after it \s+
When you use a backslash before certain letters it represents something...
\d represents a digit 0,1,2,3,4,5,6,7,8,9.
\s represents a space .
Add a plus sign (+) to the end and you can have...
\d+ a series of digits (number)
\s+ multiple spaces (typos etc.)
The same regex I gave you on your other question still applies. You just have to use preg_replace() instead.
Search for /^[\s\d]+/ and replace with the empty string. Eg:
$str = preg_replace(/^[\s\d]+/, '', $str);
This will remove digits and spaces in any order from the beginning of the string. For something that removes only a number followed by spaces, see BoltClock's answer.
If the input strings all have the same ecpected format and you will receive the same result from left trimming all numbers and spaces (no matter the order of their occurrence at the front of the string), then you don't actually need to fire up the regex engine.
I love regex, but know not to use it unless it provides a valuable advantage over a non-regex technique. Regex is often slower than non-regex techniques.
Use ltrim() with a character mask that includes spaces and digits.
Code: (Demo)
var_export(
ltrim('420 911 90210 666 keep this part', ' 0..9')
);
Output:
'keep this part'
It wouldn't matter if the string started with a space either. ltrim() will greedily remove all instances of spaces or numbers from the start of the string intil it can't anymore.

How to replace http:// or www with <a href.. in PHP

I've created this regex
(www|http://)[^ ]+
that match every http://... or www.... but I dont know how to make preg_replace that would work, I've tried
preg_replace('/((www|http://)[^ ]+)/', '\1', $str);
but it doesn't work, the result is empty string.
You need to escape the slashes in the regex because you are using slashes as the delimiter. You could also use another symbol as the delimiter.
// escaped
preg_replace('/((www|http:\/\/)[^ ]+)/', '\1', $str);
// another delimiter, '#'
preg_replace('#((www|http://)[^ ]+)#', '\1', $str);
When using the regex codes provided by the other users, be sure to add the "i" flag to enable case-insensitivity, so it'll work with both HTTP:// and http://. For example, using chaos's code:
preg_replace('!(www|http://[^ ]+)!i', '\1', $str);
First of all, you need to escape—or even better, replace—the delimeters as explained in the other answers.
preg_replace('~((www|http://)[^ ]+)~', '\1', $str);
Secondly, to further improve the regex, the $n replacement reference syntax is preferred over \\n, as stated in the manual.
preg_replace('~((www|http://)[^ ]+)~', '$1', $str);
Thirdly, you are needlessly using capturing parentheses, which only slows things down. Get rid of them. Don't forget to update $1 to $0. In case you are wondering, these are non-capturing parentheses: (?: ).
preg_replace('~(?:www|http://)[^ ]+~', '$0', $str);
Finally, I would replace [^ ]+ with the shorter and more accurate \S, which is the opposite of \s. Note that [^ ]+ does not allow spaces, but accepts newlines and tabs! \S does not.
preg_replace('~(?:www|http://)\S+~', '$0', $str);
Your main problem seems to be that you are putting everything in parentheses, so it doesn't know what "\1" is. Also, you need to escape the "/". So try this:
preg_replace('/(www|http:\/\/[^ ]+)/', '\1', $str);
Edit: It actually seems the parentheses were not an issue, I misread it. The escaping was still an issue as others also pointed out. Either solution should work.
preg_replace('!((?:www|http://)[^ ]+)!', '\1', $str);
When you use / as your pattern delimiter, having / inside your pattern will not work out well. I solved this by using ! as the pattern delimiter, but you could escape your slashes with backslashes instead.
I also didn't see any reason why you were doing two paren captures, so I removed one of them.
Part of the trouble in your situation is that you're running with warnings suppressed; if you had error_reporting(E_ALL) on, you'd have seen the messages PHP is trying to generate about your delimiter problem in your regex.
If there are multiple url contained in a string a separated by a line break instead of a space, you have to use the \S
preg_replace('/((www|http:\/\/)\S+)/', '$1', $val);

Categories