简体   繁体   中英

How do I search for a substring with a variable within a string and replace it with content that contains the substring variable with PHP?

Lets suppose I have a string:

$text = "This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD a very long string!"

I want to replace each occurrence of "exec?" in the string with some new text and at the same time I want to store the text that follows "exec" in a separate variable so it can be used when replacing the text.

For example, say I want to replace each occurrence of exec??? with, < html>???< /html>< div>???< /div> , so that the resulting string is:

$text2 = "This is my string <html>001</html><div>001</div> and this is the rest of the string <html>222</html><div>222</div> and here is even more <html>SOMEWORD</html><div>SOMEWORD</div> a very long string!"

How can I do this in PHP?

Thanks very much in advance.

Here is a way to go using preg_replace :

$text = "This is my string exec001 and this is the rest of the string exec222 and here is even more execSOMEWORD a very long string!";
$text2 = preg_replace('/\bexec(\S+)/', "<html>$1</html><div>$1</div>", $text);
echo $text2,"\n";

This will replace all occurrences of execwhatever .
\\S+ stands for any NON space character.
\\b is a word boundary.

You may find more info here .

Output:

This is my string <html>001</html><div>001</div> and this is the rest of the string <html>222</html><div>222</div> and here is even more <html>SOMEWORD</html><div>SOMEWORD</div> a very long string!

Update according to comment

If you want to replace more than one string, just do:

$text2 = preg_replace('/\bexec([^:\s]+):([^:\s]+)/', "<html>$1</html><div>$2</div>", $text);

Where [^:\\s] means any character that is not semi-colon or space

     exec\S+

This regex works replacing all exec words.See demo.

http://regex101.com/r/qK1pK7/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM