preg_match():未知修饰符“ /”

时间:2019-07-05 05:28:42

标签: php regex

当我使用此正则表达式验证URL时,显示错误...

  

preg_match():C:\ wamp64 \ www \ php \ Form中的未知修饰符“ /”   第36行的Validation \ form.php

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:validators/validators.dart';

import '../strings.dart';

class FetchDataPage extends StatefulWidget {
  final String text;
  FetchDataPage({Key key, @required this.text}) : super(key: key);

  @override
  _FetchDataState createState() => _FetchDataState();
}

class _FetchDataState extends State<FetchDataPage> {
  String _productUrl;
  Widget pageWidget;

  @override
  Widget build(BuildContext context) {
    pageWidget = _loadingWidget();
    _productUrl = widget.text;
    checkPrice(_productUrl);
    return Scaffold(
      body: Container(padding: EdgeInsets.all(20.0), child: pageWidget),
    );
  }

  Widget _loadingWidget() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Center(
          child: CircularProgressIndicator(
            backgroundColor: Colors.transparent,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.blueGrey),
          ),
        ),
        SizedBox(height: 20.0),
        Text(
          "Checking Price...",
          style: TextStyle(
            color: Colors.blueGrey,
            fontSize: 20.0,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  Widget errorWidget() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Center(
          child: Icon(
            Icons.sentiment_dissatisfied,
            color: Colors.red,
            size: 60.0,
          ),
        ),
        SizedBox(height: 20.0),
        Center(
          child: Text(
            "Product not found in database.\nPlease try again later.",
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.blueGrey,
              fontSize: 17.0,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }

  void checkPrice(String productUrl) {
    bool isUrl = isURL(productUrl, requireProtocol: true, requireTld: true);
    if (!isUrl) {
      RegExp regExp = new RegExp(r"((\w+:\/\/\S+)|(\w+[\.:]\w+\S+))[^\s,\.]");
      setState(() {
        productUrl = regExp.stringMatch(productUrl).toString();
      });
    }
    /*
    //setState is Working fine here!
    setState(() {
      pageWidget = errorWidget();
    });
    */
    var response = getLatestPrice(productUrl);
    response.then((response) {
      /*
      //It's Not Working Here :(
      setState(() {
        pageWidget = errorWidget();
      });
      */

      print("Got Response: " + response.body.toString());
      if (response.statusCode == 200) {
        var loginData = json.decode(response.body);
        bool status = loginData["status"];
        print("STATUS: " + status.toString());
        if (status) {
          //This print statement is also working fine!
          print(loginData["productUrl"]);
        } else {
          //This isn't working either
          setState(() {
            pageWidget = errorWidget();
          });
        }
      } else {
        //Not Working
        setState(() {
          pageWidget = errorWidget();
        });
      }
    });
  }
}

Future<http.Response> getLatestPrice(productUrl) async {
  var url = Strings.baseUrl + 'api/checkPrice';
  var response = await http.post(url, body: {
    'product_url': productUrl,
  }, headers: {
    HttpHeaders.authorizationHeader:
        "Basic " + base64Encode(utf8.encode('username:password'))
  });
  return response;
}

1 个答案:

答案 0 :(得分:3)

由于您使用正斜杠/作为分隔符,因此必须在正则表达式中将其转义:

if (!preg_match("/%^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu/",$website)) {
    $websiteerror = "Invalid URL";
}

现在代码为我运行,但是我仍然收到此警告:

  

PHP警告:preg_match():编译失败:\ x {}或\ o {}中的字符值在第3行的source_file.php中的偏移量106处太大

PHP似乎不完全像某些字符类中使用的十六进制范围一样。