0

I have a variable which contains email addresses.

Examples:

    $email[1]="email(at)test.com";
    $email[2]="email[at]test.com";
    $email[3]="email(a)test.com";
    $email[4]="email(alfa)test.com";
    $email[5]="email[a]test.com";

How can I to perform in PHP a regex find all between () and [] and replace with "@". so in the end it will be like this:

    $email[1]="[email protected]";
    $email[2]="[email protected]";
    $email[3]="[email protected]";
    $email[4]="[email protected]";
    $email[5]="[email protected]";

All i have at the moment is this ((([a-zA-Z]+))|([[a-zA-Z]+]))

2 Answers 2

1

Regex:

[(\[][a-z]+[)\]]

Replacement string:

@

DEMO

Example:

<?php
$string = 'email(alfa)test.com';
$pattern = '~[(\[][a-z]+[)\]]~';
$replacement = '@';
echo preg_replace($pattern, $replacement, $string);
?> //=> [email protected]
Sign up to request clarification or add additional context in comments.

Comments

1

Use this:

$replaced = preg_replace('~[([][^])]+[\])]~', '@', $yourstring);

Explanation

  • ~[([] matches an opening bracket or brace
  • [^])]+ matches any chars that are not a closing bracket or brace
  • [\])] matches a closing bracket or brace
  • We replace with @

1 Comment

FYI, this simple solution will work regardless of what we have inside the braces: for instance, (a.t.) and [a-t] will also work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.