php只有当它不是另一个子串的一部分时才会找到子串

时间:2016-08-15 16:08:13

标签: php string substring

我知道如何使用strpos查找子字符串,但我想只在字母t出现在字符串中时返回True,但如果t后跟“he”则不返回True。例如... $str="The lion and dog are hungry" 结果将是Does not contain t,因为字符串中唯一的t是单词“The”的一部分。  $str="Their bedroom is ugly"也应该返回false,因为“他们的”以T H E开头,并且字符串中没有其他t。 $str="The cat and the dog are hungry"会导致Yes, this string contains a t,因为CAT中有一个。

3 个答案:

答案 0 :(得分:2)

你需要一个负面的lookbehind regex:

/t(?!h(?:e|is))/i

请参阅regex demo

模式详情

  • t - 文字字符t
  • (?!h(?:e|is)) - 负面的lookbehind,用于检查其模式是否与当前位置之后的字符串匹配,并且如果匹配发生则返回false(返回false):
    • h - 文字h
    • (?:e|is) - eis(?:...|...)是非捕获组,不会在包含|更改的内存中保留子匹配操作者)
  • /i - 不区分大小写的修饰符以不区分大小写的方式使正则表达式匹配。

基本上,这是t(?!he|his)正则表达式的更有效版本(t未跟hehis

PHP demo

$re = '/t(?!h(?:e|is))/i';

if (preg_match($re,'The cat and the dog are hungry'))
    echo 'true';
else
    echo 'false';

答案 1 :(得分:0)

试试这个

<?php
$a = 'Their bedroom is ugly';

if (preg_match('/t(?!he)(?!his)/i',$a))
    echo 'true';
else
    echo 'false';

答案 2 :(得分:0)

你可以使用strpos检查你找到的所有'之后是否有'他':

""" An interactive script for testing Khan Academy API Authentication. 

This is an example of how to use the /api/auth2 authentication flow.

See https://github.com/Khan/khan-api/wiki/Khan-Academy-API-Authentication for
documentation.
"""

import cgi
import rauth
import SimpleHTTPServer
import SocketServer
import time
import webbrowser

# You can get a CONSUMER_KEY and CONSUMER_SECRET for your app here:
# http://www.khanacademy.org/api-apps/register
CONSUMER_SECRET = 'Redacted but auth-token works'
CONSUMER_KEY = 'Redacted'

CALLBACK_BASE = '127.0.0.1'
SERVER_URL = 'http://www.khanacademy.org'

DEFAULT_API_RESOURCE = '/api/v1/playlists'
VERIFIER = None


# Create the callback server that's used to set the oauth verifier after the
# request token is authorized.
def create_callback_server():
    class CallbackHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
        def do_GET(self):
            global VERIFIER

            params = cgi.parse_qs(self.path.split('?', 1)[1],
                keep_blank_values=False)
            VERIFIER = params['oauth_verifier'][0]

            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.end_headers()
            self.wfile.write('OAuth request token fetched and authorized;' +
                ' you can close this window.')

        def log_request(self, code='-', size='-'):
            pass

    server = SocketServer.TCPServer((CALLBACK_BASE, 0), CallbackHandler)
    return server


# Make an authenticated API call using the given rauth session.
def get_api_resource(session):
    resource_url = raw_input("Resource relative url (e.g. %s): " %
        DEFAULT_API_RESOURCE) or DEFAULT_API_RESOURCE

    url = SERVER_URL + resource_url
    split_url = url.split('?', 1)
    params = {}

    # Separate out the URL's parameters, if applicable.
    if len(split_url) == 2:
        url = split_url[0]
        params = cgi.parse_qs(split_url[1], keep_blank_values=False)

    start = time.time()
    response = session.get(url, params=params)
    end = time.time()

    print "Result\n"
    print response
    print "\nTime: %ss\n" % (end - start)

def run_tests():
    global CONSUMER_KEY, CONSUMER_SECRET, SERVER_URL

    # Set consumer key, consumer secret, and server base URL from user input or
    # use default values.
    CONSUMER_KEY = raw_input("consumer key: ") or CONSUMER_KEY
    CONSUMER_SECRET = raw_input("consumer secret: ") or CONSUMER_SECRET
    SERVER_URL = raw_input("server base url: ") or SERVER_URL

    # Create an OAuth1Service using rauth.
    service = rauth.OAuth1Service(
           name='test',
           consumer_key=CONSUMER_KEY,
           consumer_secret=CONSUMER_SECRET,
           request_token_url=SERVER_URL + '/api/auth2/request_token',
           access_token_url=SERVER_URL + '/api/auth2/access_token',
           authorize_url=SERVER_URL + '/api/auth2/authorize',
           base_url=SERVER_URL + '/api/auth2')

    callback_server = create_callback_server()

    # 1. Get a request token.
    request_token, secret_request_token = service.get_request_token(
        params={'oauth_callback': 'http://%s:%d/' %
            (CALLBACK_BASE, callback_server.server_address[1])})

    # 2. Authorize your request token.
    authorize_url = service.get_authorize_url(request_token)
    webbrowser.open(authorize_url)

    callback_server.handle_request()
    callback_server.server_close()

    # 3. Get an access token.
    session = service.get_auth_session(request_token, secret_request_token,
        params={'oauth_verifier': VERIFIER})

    # Repeatedly prompt user for a resource and make authenticated API calls.
    print
    while(True):
        get_api_resource(session)


def main():
    run_tests()

if __name__ == "__main__":
    main()

但这不是最有效的方法。恕我直言,最好的办法是使用Regex

<?php
$offest = 0;
$string = "the t the";
$result = 'No, this string does not contain t';
while ($pos1 = strpos($string,'t', $offset)) {
    if ($pos2 = strpos($string,'the',$offset) {
        if ($pos1 != $pos2) {
            $result = 'Yes, this string contains t';
        } else {
            $offset = pos1;
        }
    } else {
        $result = 'Yes, this string contains t';
    }
}
echo $result;

您还可以使用negative lookahead(个人喜爱的技巧):

$string = "the t the";
$result = 'no';
if (preg_match('/[tT][^Hh]/')) {
    $result = 'yes';
}