Conditioned search in VI

condicioned searchLet’s use something that I call conditioned search in VI: look for a text that goes or not followed by another. In the VI text editor we can use regular expressions to look for patterns in the text. This is very helpful.

Since a long time the tags to signal the start of the php code “<?” they are not accepted This is done to avoid being confused with the processing of XML declarations:

<?xml version="1.0" encoding="utf-8" ?>

For that you have to use the label “<?php” and so there is no problem. They continue to serve the “<?=” tags to insert variables directly:


Search and automatic substitution in VI

Search and replace text in vi is very easy and you can find here a small explanation.

To search and replace these labels automatically you can use the following instruction:

:%s/<?\(php\|=\)\@!/<?php /g

What this does is search the entire file (“%”) for the occurrences of the text “<?” that are not followed (“@!”) of “php” or “=” and replace (the s of the beginning) with “<?php” (what goes behind the second “/” is what will replace to what was found). At the end (behind the third “/”) comes a “g” so that the substitution is made globally, in case there is more than one occurrence per line, you can also put an “i” to indicate that it does not differentiate capital letters from lower case, it would be:

:%s/<?\(php\|=\)\@!/<?php /gi

As you can see, there are backslashes “\” in some places to differentiate those special characters from those that you should consider as text to look for, as in the parentheses that are for grouping the options.

I have added the space after php in case there is a line that has a code after <?php so that it does not get stuck and gives an error (“<?phpecho”, for example).

The syntax of \@! It is a bit confusing because it goes after the pattern that you should not find.

This can be useful to use the expression in thirst or some text search program in files that supports regular expressions but I do not know if it works in the same way.

In principle it does not seem complicated but to make it automatic you have to bear in mind that you do not have to replace all the appearances of the short tag but those that meet certain conditions, that is why the conditioned search.