Asked  7 Months ago    Answers:  5   Viewed   38 times

I'm trying to strip all characters from a string except:

  • Alphanumeric characters
  • Dollar sign ($)
  • Underscore (_)
  • Unicode characters between code points U+0080 and U+FFFF

I've got the first three conditions by doing this:

preg_replace('/[^a-zA-Zd$_]+/', '', $foo);

How do I go about matching the fourth condition? I looked at using X but there has to be a better way than listing out 65000+ characters.

 Answers

88

You can use:

$foo = preg_replace('/[^w$x{0080}-x{FFFF}]+/u', '', $foo);
  • w - is equivalent of [a-zA-Z0-9_]
  • x{0080}-x{FFFF} to match characters between code points U+0080andU+FFFF`
  • /u for unicode support in regex
Wednesday, March 31, 2021
 
Asher
answered 7 Months ago
50

To port ereg_replace to preg_replace you need to put the regex between a pair of delimiter

Also your regx is [] is invalid to be used for preg_replace as the is escaping the closing char class ]

The correct port is

preg_replace('/[\]/','',$theData) 

Also since the char class has just one char there is no real need of char class you can just say:

preg_replace('/\/','',$theData) 

Since you are replace just a single char, using regex for this is not recommended. You should be using a simple text replacement using str_replace as:

str_replace('\','',$data);
Thursday, June 24, 2021
 
Akdeniz
answered 4 Months ago
54

You need not use look arounds here. It can be written as

("[^";]*);([^"]*")

replace with 1:2

Regex Demo

Test

preg_replace ("/("[^";]*);([^"]*")/m", "\1:\2", 'asbas;"asd;";asd;asdadasd;"asd;adsas"' );
=> asbas;"asd:";asd;asdadasd;"asd:adsas"

Update:

;(?!(?:"[^"]*"|[^"])*$)

Just replace the matched ; with :

DEMO

Saturday, July 31, 2021
 
mschuett
answered 3 Months ago
11

This pattern should work for you:

[a-zA-Z][a-zA-Z0-9.,-_]{5,31}

This will match a leading letter, followed by any alpha-numeric combination up to a total of between 6 - 32 characters (for the entire string).

You can use this in PHP with:

if (preg_match('/^[a-z][a-z0-9.,-_]{5,31}$/i', $name)) {
    // you have a valid name!
}

Note, in the preg_match(), I added the i regex option to ignore case. Also, I lead the pattern with ^ to signify that the pattern has to start at the beginning of the string and I ended with a $ to signify that the pattern has to finish at the end of the string.

Monday, August 16, 2021
 
fardjad
answered 2 Months ago
89

In your example you are never incrementing the variable $j.

Try a foreach instead:

foreach($j=2; $j<=10; $j++) {
  //do your stuff
}

Or change it up to be a do-while http://php.net/manual/en/control-structures.do.while.php

Wednesday, August 18, 2021
 
Aran Mulholland
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :