I want to replace a middle string by passing the pattern. I have tried it by using pre_replace function. But it is not working for me.
$str = "Lead for Nebhub - Admark
Name: Punam Kalbande
Email: kalbandepunam@gmail.com
Phone Number: 800-703-3209
Nebhub Partner : Nebhub - Admark
Address: PO Box 830395 Miami, FL 33173
Hub : Automotive
Products: ERP, CRM, HCM, Help Desk, Marketing";
$pattern = '/^Hub :(.+)Products:$/i';
$replacement = "Logistics";
$result = preg_replace($pattern, $replacement, $str);
but the above code is only returning original string. It is not replacing with the new one.
The s-Modifier is missing in your Pattern. Further you want to match the Pattern somewhere in the middle of the Text. You used ^, which indicates the Start of the Line and $ which indicates the End of the Line. That means, the whole String must match. Use this Regex, and it will work for you.
/(Hub :)[^
]+/is
Explanation:
( start Subpattern
Hub the Word Hub
followed by a space
: followed by a Doubledot
) end Subpattern -> accessible by $1 or \1
[^
]+ match one or more Characters except a Linebreak
i Modifier for caseinsensitive Search
s Modifier to include Linebreaks
What you have to do now is to output the Subpattern in the Replacement too:
$result = preg_replace($pattern, "$1$replacement", $str);