K
K
kalinichenkoroman2020-05-05 17:13:03
PHP
kalinichenkoroman, 2020-05-05 17:13:03

How to write a regular expression with replacement?

It is necessary to leave only emails like [mailto:[email protected] [email protected]], how to do it?

$str = "
 [email protected]
  [mailto:[email protected] [email protected]]
";

$target_str = " (?!\[mailto\:)([a-z0-9._%+-][email protected](?:[A-Z0-9-]+\.)+[A-Z]{2,}(?!\]))(?!\])";
$replacement_str = " [mailto:$1 $1]";
$num_matches = 0;
$str2 = preg_replace( '/' . $target_str . '/ui', $replacement_str, $str , -1, $num_matches );
echo $str;
echo $str2;

The logic is this. If there is an email in the text, then replace it with a pattern
; if there is a pattern, then leave it as it is.
The problem is that the regular expression grabs the second email and replaces it according to the pattern.
sandbox

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2020-05-05
@kalinichenkoroman

$pattern = '/[\w.%+-][email protected](?:[a-z\d-]+\.)+[a-z]{2,}|\[mailto:[^\]]+(*SKIP)(*F)/i';

$str = preg_replace($pattern, '[mailto:$0]', $str);

sandbox.onlinephpfunctions.com/code/cd3b7b636cde9b...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question