skip to Main Content

Trying to find a solution to replace all occurance of fullstop in a sentence except if its an email.
e.g

Input:

Hello, Thanks for reaching us, we really appreciate your feedback! We are always trying to improve our product to provide you with a better experience.I will be sure to pass your suggestion onto our team for their consideration as we move forward with this. Call XYZ on 12345 or email at [email protected] if you have any question. Thank you for your email.

expected output:

Hello, Thanks for reaching us, we really appreciate your feedback! We are always trying to improve our product to provide you with a better experience.

I will be sure to pass your suggestion onto our team for their consideration as we move forward with this.

Call XYZ on 12345 or email at [email protected] if you have any question.

Thank you for your email

2

Answers


  1. I hope this help you :

    First i just found email address in text and define that’s position

    Then i remove email from text and replace all dot (.) with double end of line

    And at last i again add email to text at the correct position

    <?php
    $input = "Hello, Thanks for reaching us, we really appreciate your feedback! We are always trying to improve our product to provide you with a better experience.I will be sure to pass your suggestion onto our team for their consideration as we move forward with this. Call XYZ on 12345 or email at [email protected] if you have any question. Thank you for your email.";
    $pattern = '/b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}b/';
    preg_match_all($pattern, $input, $matches);
    $email = $matches[0][0];
    $emailpos = strpos($input, $email);
    $output = '';
    $input = str_replace($email,'',$input);
    $sentences = preg_split('/(?<=[.!?])s+/', $input);
    foreach ($sentences as $sentence) {
        $output .= rtrim($sentence, '.') . "nn";
    }
    $output = substr_replace($output, ' '.$email, $emailpos, 0);
    echo $output;
    ?>
    
    Login or Signup to reply.
    • Split the text based on spaces.

    • Consider each continuous string of characters as tokens.

    • For each token, check if we have a period character . and if we have, check if it’s an email using filter_var. The regex approach to check if a string is an email is too complicated. See this.

    • If it’s not an email, replace the period character with a period character and new lines.

    • Implode the array back to a string based on a single space. Your text is now formatted with new lines.

    Snippet:

    <?php
    
    $d = explode(" ", trim($str));
    
    foreach($d as &$token){
        if(strpos($token, '.') !== false && !filter_var($token, FILTER_VALIDATE_EMAIL)) {
           $token = str_replace('.', ".nn", $token);
        }
    }
    
    echo implode(" ", $d);
    

    Live Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search