نص عربى English text

Regex to match anything

I know it seems a bit redundant but I’d like a regex to match anything. At the moment we are using ^*$ but it doesn’t seem to match no matter what the text. I do a manual check for no text but the test view we use is always validated with a regex. However, sometimes we need it to validate anything using a regex. i.e. it doesn’t matter what is in the text field, it can be anything. I don’t actually produce the regex and I’m a complete beginner with them.

4 Answers 4

The regex .* will match anything (including the empty string, as Junuxx points out).

Checking for nothing doesn’t matter too much as I’m doing that outside of the regex. I will try both though, thanks.

The chosen answer is slightly incorrect, as it wont match line breaks or returns. This regex to match anything is useful if your desired selection includes any line breaks:

[\s\S] matches a character that is either a whitespace character (including line break characters), or a character that is not a whitespace character. Since all characters are either whitespace or non-whitespace, this character class matches any character. the + matches one or more of the preceding expression

^ is the beginning-of-line anchor, so it will be a «zero-width match,» meaning it won’t match any actual characters (and the first character matched after the ^ will be the first character of the string). Similarly, $ is the end-of-line anchor.

Читайте также:  Python уникальные значения строки

* is a quantifier. It will not by itself match anything; it only indicates how many times a portion of the pattern can be matched. Specifically, it indicates that the previous «atom» (that is, the previous character or the previous parenthesized sub-pattern) can match any number of times.

To actually match some set of characters, you need to use a character class. As RichieHindle pointed out, the character class you need here is . , which represents any character except newlines (and it can be made to match newlines as well using the appropriate flag). So .* represents * (any number) matches on . (any character). Similarly, .+ represents + (at least one) matches on . (any character).

Источник

PHP Regular Expressions

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.

In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~.

Regular Expression Functions

PHP provides a variety of functions that allow you to use regular expressions. The preg_match() , preg_match_all() and preg_replace() functions are some of the most commonly used ones:

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced with another string

Using preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern.

Example

Use a regular expression to do a case-insensitive search for «w3schools» in a string:

Using preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a string.

Example

Use a regular expression to do a case-insensitive count of the number of occurrences of «ain» in a string:

$str = «The rain in SPAIN falls mainly on the plains.»;
$pattern = «/ain/i»;
echo preg_match_all($pattern, $str); // Outputs 4
?>

Using preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another string.

Example

Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:

$str = «Visit Microsoft!»;
$pattern = «/microsoft/i»;
echo preg_replace($pattern, «W3Schools», $str); // Outputs «Visit W3Schools!»
?>

Regular Expression Modifiers

Modifiers can change how a search is performed.

Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)
u Enables correct matching of UTF-8 encoded patterns

Regular Expression Patterns

Brackets are used to find a range of characters:

Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
4 Find one character from the range 0 to 9

Metacharacters

Metacharacters are characters with a special meaning:

Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n Matches any string that contains a sequence of X n‘s
n Matches any string that contains a sequence of X to Y n‘s
n Matches any string that contains a sequence of at least X n‘s

Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. For example, to search for one or more question marks you can use the following expression: $pattern = ‘/\?+/’;

Grouping

You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match.

Example

Use grouping to search for the word «banana» by looking for ba followed by two instances of na:

Complete RegExp Reference

The reference contains descriptions and examples of all Regular Expression functions.

Источник

regex to match any string whether Unicode or not?

If your PCRE is compiled with unicode support, you can just match against the letter space from the unicode standard.

Please note the u-modifier, that enables unicode matching.

$string = ""; $pattern = '/"; $pattern = '/(.*)/u'; if (preg_match_all($pattern, $string, $matches, PREG_SET_ORDER)) < print($matches[0][1]."\n"); >else < echo 'No matches.'; >?></code> </pre> <pre><code>rasjani@laptop:~$ php unitest.php نص عربى English text rasjani@laptop:~$</code> </pre> <p>it works well for me if the title was in page with UTF8 ENCODED ONLY !! but if the page was encoded in windows-1256 doesn’t work</p> <p>@D3VELOPER: correct. To do what you want with PCRE you need to normalize the encoding before you apply the regex. You can use iconv to convert from windows-1256 to UTF-8.</p> <p>The (. ) will only match something which is exactly 6 characters long, and it will only match ‘?’. To match ‘any’ character, use ‘.’ and to match repeating number of them use ‘.*’</p> <p>Matching HTML tags like that is not easy in regex, so you should probably use a HTML parser for that instead.</p> <p>As an aproximation you could do something like /([^<]*)<\/title>/ Which will almost work, as long as your text does not contain a ‘</p> <p>This question is in a collective: a subcommunity defined by tags with relevant content and experts.</p> <p><a href="https://stackoverflow.com/questions/6612899/regex-to-match-any-string-whether-unicode-or-not">Источник</a></p> <h2 id="empty-regex-matches-any-string">empty regex matches any string</h2> <p>I was trying to find a regex that matches any string! and after some search I found almost all the answers says that [\s\S] will match any string as said here or .* as said here But while playing a bit with PHP preg_match I found that an empty regex is matching any string!</p> <pre><code>if(preg_match("//u", "")) echo "empty string matchs\n"; else echo "empty string does not match\n"; if(preg_match("//u", "abc")) echo "abc matchs\n"; else echo "abc does not match\n"; if(preg_match("//u", "\n")) echo "new line matchs\n"; else echo "new line does not match\n"; if(preg_match("//u", "/")) echo "/ matchs\n"; else echo "/ does not match\n"; exit;</code> </pre> <pre><code>empty string matchs abc matchs new line matchs / matchs</code> </pre> <p>live demo (https://eval.in/845001) <strong>Can I use this empty regex safely to match anything ? and what does an empty regex mean ?</strong> <em>If you are asking why would I need a regex that matches anything, that is because I’m using a function that requires a regex parameter as part of it’s string validation functionality and I want it to accept anything.</em></p> <h2 id="2-answers-2">2 Answers 2</h2> <p>An empty regex pattern // matches at start, end and any position between characters in a string. See this demo at eval.in preg_match_all(‘//’, «foo», $out); which returns 4 empty matches:</p> <p>As preg_match would just check for the first match it should be fine to use the empty pattern. However generally I’d probably prefer /^/ which matches <em>start of the string</em> that every string has.</p> [\s\S] (shorts for whitespaces together with non-whitespaces in a character class) means <em>just any character</em> and is usually used line-break related to also match newlines where there is no flag available for making the dot match linebreaks. Often used with JS regex which does not support s flag. Similar are [\D\d] (digits and non-digits), [\w\W] (word characters and non word characters). Also possible with JS regex is [^] a negated empty character class for «not nothing». <p>To use /[\s\S]/ or one of the others without quantifier will require at least one character.</p> <p>Further to mention that in your patterns you use the u flag for unicode regex. There is probably no reason to use this flag together with an empty pattern or just checking for start of the string. Interesting with pcre unicode regex might be the following escape sequences.</p> <ul> <li>\X matches an unicode grapheme. Similar the dot in u -mode (but not newlines).</li> <li>\C matches one data unit (similar using the dot without u flag on unicode input).</li> </ul> <p>Well, I don’t really see why one would need a pattern to match any string, but wrote for interest 🙂</p> <p><a href="https://stackoverflow.com/questions/45665579/empty-regex-matches-any-string">Источник</a></p> <div class="fpm_end"></div> </div><!-- .entry-content --> </article> <div class="rating-box"> <div class="rating-box__header">Оцените статью</div> <div class="wp-star-rating js-star-rating star-rating--score-0" data-post-id="171652" data-rating-count="0" data-rating-sum="0" data-rating-value="0"><span class="star-rating-item js-star-rating-item" data-score="1"><svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" class="i-ico"><path fill="currentColor" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" class="ico-star"></path></svg></span><span class="star-rating-item js-star-rating-item" data-score="2"><svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" class="i-ico"><path fill="currentColor" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" class="ico-star"></path></svg></span><span class="star-rating-item js-star-rating-item" data-score="3"><svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" class="i-ico"><path fill="currentColor" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" class="ico-star"></path></svg></span><span class="star-rating-item js-star-rating-item" data-score="4"><svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" class="i-ico"><path fill="currentColor" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" class="ico-star"></path></svg></span><span class="star-rating-item js-star-rating-item" data-score="5"><svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" class="i-ico"><path fill="currentColor" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z" class="ico-star"></path></svg></span></div> </div> <div class="entry-social"> <div class="social-buttons"><span class="social-button social-button--vkontakte" data-social="vkontakte" data-image=""></span><span class="social-button social-button--facebook" data-social="facebook"></span><span class="social-button social-button--telegram" data-social="telegram"></span><span class="social-button social-button--odnoklassniki" data-social="odnoklassniki"></span><span class="social-button social-button--twitter" data-social="twitter"></span><span class="social-button social-button--sms" data-social="sms"></span><span class="social-button social-button--whatsapp" data-social="whatsapp"></span></div> </div> <meta itemprop="author" content="admin"> <meta itemscope itemprop="mainEntityOfPage" itemType="https://schema.org/WebPage" itemid="https://business-programming.ru/english-text/" content="نص عربى English text"> <meta itemprop="dateModified" content="2023-08-26"> <meta itemprop="datePublished" content="2023-08-29T07:36:31+03:00"> <div itemprop="publisher" itemscope itemtype="https://schema.org/Organization" style="display: none;"><meta itemprop="name" content="Программирование"><meta itemprop="telephone" content="Программирование"><meta itemprop="address" content="https://business-programming.ru"></div> </main><!-- #main --> </div><!-- #primary --> <aside id="secondary" class="widget-area" itemscope itemtype="http://schema.org/WPSideBar"> <div class="sticky-sidebar js-sticky-sidebar"> <div id="block-2" class="widget widget_block"><div class="flatPM_sidebar" data-top="70"> <div id="Q_sidebar"></div> </div></div> </div> </aside><!-- #secondary --> <div id="related-posts" class="related-posts fixed"><div class="related-posts__header">Вам также может понравиться</div><div class="post-cards post-cards--vertical"> <div class="post-card post-card--related post-card--thumbnail-no"> <div class="post-card__title"><a href="https://business-programming.ru/yaschiki-s-usami-python/">Ящики с усами python</a></div><div class="post-card__description">pandas.plotting.boxplot# Make a box-and-whisker plot</div> </div> <div class="post-card post-card--related post-card--thumbnail-no"> <div class="post-card__title"><a href="https://business-programming.ru/primer-ispolzovaniya-svoystva-css-table-layout-74/">Пример использования свойства CSS table-layout.</a></div><div class="post-card__description">table-layout¶ Свойство table-layout определяет, как</div> </div> <div class="post-card post-card--related post-card--thumbnail-no"> <div class="post-card__title"><a href="https://business-programming.ru/primer-ispolzovaniya-svoystva-css-table-layout-73/">Пример использования свойства CSS table-layout.</a></div><div class="post-card__description">HTML Размеры таблицы HTML таблицы могут иметь разные</div> </div> <div class="post-card post-card--related post-card--thumbnail-no"> <div class="post-card__title"><a href="https://business-programming.ru/primer-ispolzovaniya-svoystva-css-table-layout-72/">Пример использования свойства CSS table-layout.</a></div><div class="post-card__description">table-layout¶ Свойство table-layout определяет, как</div> </div> </div></div> </div><!--.site-content-inner--> </div><!--.site-content--> <div class="site-footer-container "> <div class="footer-navigation fixed" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div class="main-navigation-inner full"> <div class="menu-tehnicheskoe-menyu-container"><ul id="footer_menu" class="menu"><li id="menu-item-12637" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12637"><a href="https://business-programming.ru/pravoobladatelyam/">Правообладателям</a></li> <li id="menu-item-12638" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12638"><a href="https://business-programming.ru/politika-konfidentsialnosti/">Политика конфиденциальности</a></li> <li id="menu-item-12639" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12639"><a href="https://business-programming.ru/kontakty/">Контакты</a></li> </ul></div> </div> </div><!--footer-navigation--> <footer id="colophon" class="site-footer site-footer--style-gray full"> <div class="site-footer-inner fixed"> <div class="footer-bottom"> <div class="footer-info"> © 2024 Программирование </div> <div class="footer-counters"><!-- Yandex.Metrika counter --> <script type="text/javascript" >
   (function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
   m[i].l=1*new Date();
   for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
   k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
   (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

   ym(97921369, "init", {
        clickmap:true,
        trackLinks:true,
        accurateTrackBounce:true,
        webvisor:true
   });
</script> <noscript><div><img src="https://mc.yandex.ru/watch/97921369" style="position:absolute; left:-9999px;" alt=""/></div></noscript> <!-- /Yandex.Metrika counter --></div></div> </div> </footer><!--.site-footer--> </div> <button type="button" class="scrolltop js-scrolltop"></button> </div><!-- #page --> <script>var pseudo_links = document.querySelectorAll(".pseudo-clearfy-link");for (var i=0;i<pseudo_links.length;i++ ) { pseudo_links[i].addEventListener("click", function(e){   window.open( e.target.getAttribute("data-uri") ); }); }</script><script type="text/javascript" id="reboot-scripts-js-extra">
/* <![CDATA[ */
var settings_array = {"rating_text_average":"\u0441\u0440\u0435\u0434\u043d\u0435\u0435","rating_text_from":"\u0438\u0437","lightbox_display":"1","sidebar_fixed":"1"};
var wps_ajax = {"url":"https:\/\/business-programming.ru\/wp-admin\/admin-ajax.php","nonce":"b152cf5421"};
/* ]]> */
</script> <script type="text/javascript" src="https://business-programming.ru/wp-content/themes/reboot/assets/js/scripts.min.js" id="reboot-scripts-js"></script> <script>window.lazyLoadOptions = [{
                elements_selector: "img[data-lazy-src],.rocket-lazyload,iframe[data-lazy-src]",
                data_src: "lazy-src",
                data_srcset: "lazy-srcset",
                data_sizes: "lazy-sizes",
                class_loading: "lazyloading",
                class_loaded: "lazyloaded",
                threshold: 300,
                callback_loaded: function(element) {
                    if ( element.tagName === "IFRAME" && element.dataset.rocketLazyload == "fitvidscompatible" ) {
                        if (element.classList.contains("lazyloaded") ) {
                            if (typeof window.jQuery != "undefined") {
                                if (jQuery.fn.fitVids) {
                                    jQuery(element).parent().fitVids();
                                }
                            }
                        }
                    }
                }},{
				elements_selector: ".rocket-lazyload",
				data_src: "lazy-src",
				data_srcset: "lazy-srcset",
				data_sizes: "lazy-sizes",
				class_loading: "lazyloading",
				class_loaded: "lazyloaded",
				threshold: 300,
			}];
        window.addEventListener('LazyLoad::Initialized', function (e) {
            var lazyLoadInstance = e.detail.instance;

            if (window.MutationObserver) {
                var observer = new MutationObserver(function(mutations) {
                    var image_count = 0;
                    var iframe_count = 0;
                    var rocketlazy_count = 0;

                    mutations.forEach(function(mutation) {
                        for (var i = 0; i < mutation.addedNodes.length; i++) {
                            if (typeof mutation.addedNodes[i].getElementsByTagName !== 'function') {
                                continue;
                            }

                            if (typeof mutation.addedNodes[i].getElementsByClassName !== 'function') {
                                continue;
                            }

                            images = mutation.addedNodes[i].getElementsByTagName('img');
                            is_image = mutation.addedNodes[i].tagName == "IMG";
                            iframes = mutation.addedNodes[i].getElementsByTagName('iframe');
                            is_iframe = mutation.addedNodes[i].tagName == "IFRAME";
                            rocket_lazy = mutation.addedNodes[i].getElementsByClassName('rocket-lazyload');

                            image_count += images.length;
			                iframe_count += iframes.length;
			                rocketlazy_count += rocket_lazy.length;

                            if(is_image){
                                image_count += 1;
                            }

                            if(is_iframe){
                                iframe_count += 1;
                            }
                        }
                    } );

                    if(image_count > 0 || iframe_count > 0 || rocketlazy_count > 0){
                        lazyLoadInstance.update();
                    }
                } );

                var b      = document.getElementsByTagName("body")[0];
                var config = { childList: true, subtree: true };

                observer.observe(b, config);
            }
        }, false);</script><script data-no-minify="1" async src="https://business-programming.ru/wp-content/plugins/rocket-lazy-load/assets/js/16.1/lazyload.min.js"></script><script>function lazyLoadThumb(e,alt){var t='<img loading="lazy" src="https://i.ytimg.com/vi/ID/hqdefault.jpg" alt="" width="480" height="360">',a='<button class="play" aria-label="play Youtube video"></button>';t=t.replace('alt=""','alt="'+alt+'"');return t.replace("ID",e)+a}function lazyLoadYoutubeIframe(){var e=document.createElement("iframe"),t="ID?autoplay=1";t+=0===this.parentNode.dataset.query.length?'':'&'+this.parentNode.dataset.query;e.setAttribute("src",t.replace("ID",this.parentNode.dataset.src)),e.setAttribute("frameborder","0"),e.setAttribute("allowfullscreen","1"),e.setAttribute("allow", "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"),this.parentNode.parentNode.replaceChild(e,this.parentNode)}document.addEventListener("DOMContentLoaded",function(){var e,t,p,a=document.getElementsByClassName("rll-youtube-player");for(t=0;t<a.length;t++)e=document.createElement("div"),e.setAttribute("data-id",a[t].dataset.id),e.setAttribute("data-query", a[t].dataset.query),e.setAttribute("data-src", a[t].dataset.src),e.innerHTML=lazyLoadThumb(a[t].dataset.id,a[t].dataset.alt),a[t].appendChild(e),p=e.querySelector('.play'),p.onclick=lazyLoadYoutubeIframe});</script> </body> </html>